- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 265 /* JsxExpression */) {
+ if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) {
return true;
}
//
{
// |
// } < /div>
- if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 265 /* JsxExpression */) {
+ if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) {
return true;
}
//
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 258 /* JsxClosingElement */) {
+ if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) {
return true;
}
return false;
@@ -87827,7 +88596,7 @@ var ts;
return ts.isJsxText(node) && node.containsOnlyWhiteSpaces;
}
function isInTemplateString(sourceFile, position) {
- var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
+ var token = getTokenAtPosition(sourceFile, position);
return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
}
ts.isInTemplateString = isInTemplateString;
@@ -87869,7 +88638,7 @@ var ts;
if (!token || !ts.isIdentifier(token))
return undefined;
if (!remainingLessThanTokens) {
- return { called: token, nTypeArguments: nTypeArguments };
+ return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments };
}
remainingLessThanTokens--;
break;
@@ -87939,19 +88708,13 @@ var ts;
* @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)
* @param predicate Additional predicate to test on the comment range.
*/
- function isInComment(sourceFile, position, tokenAtPosition, predicate) {
- return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ false, /*precedingToken*/ undefined, tokenAtPosition, predicate);
+ function isInComment(sourceFile, position, tokenAtPosition) {
+ return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition);
}
ts.isInComment = isInComment;
function hasDocComment(sourceFile, position) {
- var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
- // First, we have to see if this position actually landed in a comment.
- var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
- return ts.forEach(commentRanges, jsDocPrefix);
- function jsDocPrefix(c) {
- var text = sourceFile.text;
- return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*";
- }
+ var token = getTokenAtPosition(sourceFile, position);
+ return !!ts.findAncestor(token, ts.isJSDoc);
}
ts.hasDocComment = hasDocComment;
function nodeHasTokens(n, sourceFile) {
@@ -87960,7 +88723,7 @@ var ts;
return n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node) {
- var flags = ts.getCombinedModifierFlags(node);
+ var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */;
var result = [];
if (flags & 8 /* Private */)
result.push("private" /* privateMemberModifier */);
@@ -87980,10 +88743,10 @@ var ts;
}
ts.getNodeModifiers = getNodeModifiers;
function getTypeArgumentOrTypeParameterList(node) {
- if (node.kind === 162 /* TypeReference */ || node.kind === 187 /* CallExpression */) {
+ if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) {
return node.typeArguments;
}
- if (ts.isFunctionLike(node) || node.kind === 235 /* ClassDeclaration */ || node.kind === 236 /* InterfaceDeclaration */) {
+ if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) {
return node.typeParameters;
}
return undefined;
@@ -88028,18 +88791,18 @@ var ts;
}
ts.cloneCompilerOptions = cloneCompilerOptions;
function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
- if (node.kind === 183 /* ArrayLiteralExpression */ ||
- node.kind === 184 /* ObjectLiteralExpression */) {
+ if (node.kind === 185 /* ArrayLiteralExpression */ ||
+ node.kind === 186 /* ObjectLiteralExpression */) {
// [a,b,c] from:
// [a, b, c] = someExpression;
- if (node.parent.kind === 200 /* BinaryExpression */ &&
+ if (node.parent.kind === 202 /* BinaryExpression */ &&
node.parent.left === node &&
node.parent.operatorToken.kind === 58 /* EqualsToken */) {
return true;
}
// [a, b, c] from:
// for([a, b, c] of expression)
- if (node.parent.kind === 222 /* ForOfStatement */ &&
+ if (node.parent.kind === 225 /* ForOfStatement */ &&
node.parent.initializer === node) {
return true;
}
@@ -88047,7 +88810,7 @@ var ts;
// [x, [a, b, c] ] = someExpression
// or
// {x, a: {a, b, c} } = someExpression
- if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 270 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
+ if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
return true;
}
}
@@ -88055,19 +88818,17 @@ var ts;
}
ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
function isInReferenceComment(sourceFile, position) {
- return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) {
- var commentText = sourceFile.text.substring(c.pos, c.end);
- return tripleSlashDirectivePrefixRegex.test(commentText);
- });
+ return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true);
}
ts.isInReferenceComment = isInReferenceComment;
function isInNonReferenceComment(sourceFile, position) {
- return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) {
- var commentText = sourceFile.text.substring(c.pos, c.end);
- return !tripleSlashDirectivePrefixRegex.test(commentText);
- });
+ return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false);
}
ts.isInNonReferenceComment = isInNonReferenceComment;
+ function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) {
+ var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined);
+ return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end));
+ }
function createTextSpanFromNode(node, sourceFile) {
return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd());
}
@@ -88181,13 +88942,17 @@ var ts;
QuotePreference[QuotePreference["Single"] = 0] = "Single";
QuotePreference[QuotePreference["Double"] = 1] = "Double";
})(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {}));
+ function quotePreferenceFromString(str, sourceFile) {
+ return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */;
+ }
+ ts.quotePreferenceFromString = quotePreferenceFromString;
function getQuotePreference(sourceFile, preferences) {
if (preferences.quotePreference) {
return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */;
}
else {
- var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports);
- return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile) ? 0 /* Single */ : 1 /* Double */;
+ var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral);
+ return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */;
}
}
ts.getQuotePreference = getQuotePreference;
@@ -88267,6 +89032,37 @@ var ts;
return NodeSet;
}());
ts.NodeSet = NodeSet;
+ var NodeMap = /** @class */ (function () {
+ function NodeMap() {
+ this.map = ts.createMap();
+ }
+ NodeMap.prototype.get = function (node) {
+ var res = this.map.get(String(ts.getNodeId(node)));
+ return res && res.value;
+ };
+ NodeMap.prototype.getOrUpdate = function (node, setValue) {
+ var res = this.get(node);
+ if (res)
+ return res;
+ var value = setValue();
+ this.set(node, value);
+ return value;
+ };
+ NodeMap.prototype.set = function (node, value) {
+ this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
+ };
+ NodeMap.prototype.has = function (node) {
+ return this.map.has(String(ts.getNodeId(node)));
+ };
+ NodeMap.prototype.forEach = function (cb) {
+ this.map.forEach(function (_a) {
+ var node = _a.node, value = _a.value;
+ return cb(value, node);
+ });
+ };
+ return NodeMap;
+ }());
+ ts.NodeMap = NodeMap;
function getParentNodeInSpan(node, file, span) {
if (!node)
return undefined;
@@ -88282,6 +89078,10 @@ var ts;
return ts.textSpanContainsPosition(span, node.getStart(file)) &&
node.getEnd() <= ts.textSpanEnd(span);
}
+ function findModifier(node, kind) {
+ return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; });
+ }
+ ts.findModifier = findModifier;
/* @internal */
function insertImport(changes, sourceFile, importDecl) {
var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax);
@@ -88494,7 +89294,7 @@ var ts;
ts.signatureToDisplayParts = signatureToDisplayParts;
function isImportOrExportSpecifierName(location) {
return !!location.parent &&
- (location.parent.kind === 248 /* ImportSpecifier */ || location.parent.kind === 252 /* ExportSpecifier */) &&
+ (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) &&
location.parent.propertyName === location;
}
ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
@@ -89112,10 +89912,10 @@ var ts;
// That means we're calling back into the host around every 1.2k of the file we process.
// Lib.d.ts has similar numbers.
switch (kind) {
- case 239 /* ModuleDeclaration */:
- case 235 /* ClassDeclaration */:
- case 236 /* InterfaceDeclaration */:
- case 234 /* FunctionDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 237 /* FunctionDeclaration */:
cancellationToken.throwIfCancellationRequested();
}
}
@@ -89327,18 +90127,18 @@ var ts;
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 293 /* JSDocParameterTag */:
+ case 296 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 297 /* JSDocTemplateTag */:
+ case 300 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 296 /* JSDocTypeTag */:
+ case 299 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 294 /* JSDocReturnTag */:
+ case 297 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -89425,22 +90225,22 @@ var ts;
}
function tryClassifyJsxElementName(token) {
switch (token.parent && token.parent.kind) {
- case 257 /* JsxOpeningElement */:
+ case 260 /* JsxOpeningElement */:
if (token.parent.tagName === token) {
return 19 /* jsxOpenTagName */;
}
break;
- case 258 /* JsxClosingElement */:
+ case 261 /* JsxClosingElement */:
if (token.parent.tagName === token) {
return 20 /* jsxCloseTagName */;
}
break;
- case 256 /* JsxSelfClosingElement */:
+ case 259 /* JsxSelfClosingElement */:
if (token.parent.tagName === token) {
return 21 /* jsxSelfClosingTagName */;
}
break;
- case 262 /* JsxAttribute */:
+ case 265 /* JsxAttribute */:
if (token.parent.name === token) {
return 22 /* jsxAttribute */;
}
@@ -89469,17 +90269,17 @@ var ts;
var parent = token.parent;
if (tokenKind === 58 /* EqualsToken */) {
// the '=' in a variable declaration is special cased here.
- if (parent.kind === 232 /* VariableDeclaration */ ||
+ if (parent.kind === 235 /* VariableDeclaration */ ||
parent.kind === 152 /* PropertyDeclaration */ ||
parent.kind === 149 /* Parameter */ ||
- parent.kind === 262 /* JsxAttribute */) {
+ parent.kind === 265 /* JsxAttribute */) {
return 5 /* operator */;
}
}
- if (parent.kind === 200 /* BinaryExpression */ ||
- parent.kind === 198 /* PrefixUnaryExpression */ ||
- parent.kind === 199 /* PostfixUnaryExpression */ ||
- parent.kind === 201 /* ConditionalExpression */) {
+ if (parent.kind === 202 /* BinaryExpression */ ||
+ parent.kind === 200 /* PrefixUnaryExpression */ ||
+ parent.kind === 201 /* PostfixUnaryExpression */ ||
+ parent.kind === 203 /* ConditionalExpression */) {
return 5 /* operator */;
}
}
@@ -89490,7 +90290,7 @@ var ts;
}
else if (tokenKind === 9 /* StringLiteral */) {
// TODO: GH#18217
- return token.parent.kind === 262 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
+ return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
}
else if (tokenKind === 12 /* RegularExpressionLiteral */) {
// TODO: we should get another classification type for these literals.
@@ -89506,7 +90306,7 @@ var ts;
else if (tokenKind === 71 /* Identifier */) {
if (token) {
switch (token.parent.kind) {
- case 235 /* ClassDeclaration */:
+ case 238 /* ClassDeclaration */:
if (token.parent.name === token) {
return 11 /* className */;
}
@@ -89516,17 +90316,17 @@ var ts;
return 15 /* typeParameterName */;
}
return;
- case 236 /* InterfaceDeclaration */:
+ case 239 /* InterfaceDeclaration */:
if (token.parent.name === token) {
return 13 /* interfaceName */;
}
return;
- case 238 /* EnumDeclaration */:
+ case 241 /* EnumDeclaration */:
if (token.parent.name === token) {
return 12 /* enumName */;
}
return;
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
if (token.parent.name === token) {
return 14 /* moduleName */;
}
@@ -89578,12 +90378,12 @@ var ts;
});
}
function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) {
- return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker));
+ return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker));
}
PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames;
- function getStringLiteralCompletionsFromModuleNamesWorker(node, compilerOptions, host, typeChecker) {
+ function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) {
var literalValue = ts.normalizeSlashes(node.text);
- var scriptPath = node.getSourceFile().path;
+ var scriptPath = sourceFile.path;
var scriptDirectory = ts.getDirectoryPath(scriptPath);
if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) {
var extensions = getSupportedExtensionsForModuleResolution(compilerOptions);
@@ -89595,7 +90395,6 @@ var ts;
}
}
else {
- // Check for node modules
return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
}
}
@@ -89761,14 +90560,16 @@ var ts;
function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) {
if (!ts.endsWith(path, "*")) {
// For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion.
- return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" /* directory */ }] : ts.emptyArray;
+ return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray;
}
var pathPrefix = path.slice(0, path.length - 1);
- if (!ts.startsWith(fragment, pathPrefix)) {
- return [{ name: pathPrefix, kind: "directory" /* directory */ }];
+ var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix);
+ return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) {
+ return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host);
+ });
+ function justPathMappingName(name) {
+ return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray;
}
- var remainingFragment = fragment.slice(pathPrefix.length);
- return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); });
}
function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) {
if (!host.readDirectory) {
@@ -89825,7 +90626,7 @@ var ts;
return nonRelativeModuleNames;
}
function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) {
- var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, position);
var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos);
var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; });
if (!range) {
@@ -90298,11 +91099,11 @@ var ts;
})(StringLiteralCompletionKind || (StringLiteralCompletionKind = {}));
function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) {
switch (node.parent.kind) {
- case 178 /* LiteralType */:
+ case 180 /* LiteralType */:
switch (node.parent.parent.kind) {
case 162 /* TypeReference */:
return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false };
- case 176 /* IndexedAccessType */:
+ case 178 /* IndexedAccessType */:
// Get all apparent property names
// i.e. interface Foo {
// foo: string;
@@ -90310,12 +91111,12 @@ var ts;
// }
// let x: Foo["/*completion position*/"]
return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType));
- case 179 /* ImportType */:
+ case 181 /* ImportType */:
return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) };
default:
return undefined;
}
- case 270 /* PropertyAssignment */:
+ case 273 /* PropertyAssignment */:
if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) {
// Get quoted name of properties of the object literal expression
// i.e. interface ConfigFiles {
@@ -90332,7 +91133,7 @@ var ts;
return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent));
}
return fromContextualType();
- case 186 /* ElementAccessExpression */: {
+ case 188 /* ElementAccessExpression */: {
var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression;
if (node === argumentExpression) {
// Get all names of properties on the expression
@@ -90345,8 +91146,8 @@ var ts;
}
return undefined;
}
- case 187 /* CallExpression */:
- case 188 /* NewExpression */:
+ case 189 /* CallExpression */:
+ case 190 /* NewExpression */:
if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) {
var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile);
// Get string literal completions from specialized signatures of the target
@@ -90355,9 +91156,9 @@ var ts;
return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType();
}
// falls through (is `require("")` or `import("")`)
- case 244 /* ImportDeclaration */:
- case 250 /* ExportDeclaration */:
- case 254 /* ExternalModuleReference */:
+ case 247 /* ImportDeclaration */:
+ case 253 /* ExportDeclaration */:
+ case 257 /* ExternalModuleReference */:
// Get all known external module names or complete a path to a module
// i.e. import * as ns from "/*completion position*/";
// var y = import("/*completion position*/");
@@ -90434,7 +91235,7 @@ var ts;
|| ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target)
: symbol.name;
}
- function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, getCanonicalFileName, preferences, cancellationToken) {
+ function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) {
var typeChecker = program.getTypeChecker();
var compilerOptions = program.getCompilerOptions();
var name = entryId.name;
@@ -90463,7 +91264,7 @@ var ts;
}
case "symbol": {
var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken;
- var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay;
+ var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay;
return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
}
case "literal": {
@@ -90506,14 +91307,14 @@ var ts;
function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) {
return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source };
}
- function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles, preferences) {
+ function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, allSourceFiles, preferences) {
var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)];
if (!symbolOriginInfo || symbolOriginInfo.type !== "export") {
return { codeActions: undefined, sourceDisplay: undefined };
}
var moduleSymbol = symbolOriginInfo.moduleSymbol;
var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker));
- var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction;
+ var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, allSourceFiles, formatContext, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction;
return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] };
}
function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) {
@@ -90554,11 +91355,11 @@ var ts;
return getContextualTypeFromParent(previousToken, checker);
case 58 /* EqualsToken */:
switch (parent.kind) {
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
return checker.getContextualType(parent.initializer); // TODO: GH#18217
- case 200 /* BinaryExpression */:
+ case 202 /* BinaryExpression */:
return checker.getTypeAtLocation(parent.left);
- case 262 /* JsxAttribute */:
+ case 265 /* JsxAttribute */:
return checker.getContextualTypeForJsxAttribute(parent);
default:
return undefined;
@@ -90568,7 +91369,7 @@ var ts;
case 73 /* CaseKeyword */:
return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker);
case 17 /* OpenBraceToken */:
- return ts.isJsxExpression(parent) && parent.parent.kind !== 255 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined;
+ return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined;
default:
var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile);
return argInfo
@@ -90583,15 +91384,15 @@ var ts;
function getContextualTypeFromParent(node, checker) {
var parent = node.parent;
switch (parent.kind) {
- case 188 /* NewExpression */:
+ case 190 /* NewExpression */:
return checker.getContextualType(parent);
- case 200 /* BinaryExpression */: {
+ case 202 /* BinaryExpression */: {
var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
return isEqualityOperatorKind(operatorToken.kind)
? checker.getTypeAtLocation(node === right ? left : right)
: checker.getContextualType(node);
}
- case 266 /* CaseClause */:
+ case 269 /* CaseClause */:
return parent.expression === node ? getSwitchedType(parent, checker) : undefined;
default:
return checker.getContextualType(node);
@@ -90607,16 +91408,15 @@ var ts;
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 274 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
var start = ts.timestamp();
- var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853
+ var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853
// We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.)
log("getCompletionData: Get current token: " + (ts.timestamp() - start));
start = ts.timestamp();
- // Completion not allowed inside comments, bail out if this is the case
var insideComment = ts.isInComment(sourceFile, position, currentToken);
log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
var insideJsDocTagTypeExpression = false;
@@ -90659,11 +91459,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 278 /* JSDocTypeExpression */) {
- currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true);
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) {
+ currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 299 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 302 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -90681,7 +91481,7 @@ var ts;
}
}
start = ts.timestamp();
- var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217
+ var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217
log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start));
// The decision to provide completion depends on the contextToken, which is determined through the previousToken.
// Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file
@@ -90690,7 +91490,7 @@ var ts;
// Skip this partial identifier and adjust the contextToken to the token that precedes it.
if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
var start_1 = ts.timestamp();
- contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); // TODO: GH#18217
+ contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
}
// Find the node where completion is requested on.
@@ -90713,15 +91513,15 @@ var ts;
if (contextToken.kind === 23 /* DotToken */) {
isRightOfDot = true;
switch (parent.kind) {
- case 185 /* PropertyAccessExpression */:
+ case 187 /* PropertyAccessExpression */:
propertyAccessToConvert = parent;
node = propertyAccessToConvert.expression;
break;
case 146 /* QualifiedName */:
node = parent.left;
break;
- case 179 /* ImportType */:
- case 210 /* MetaProperty */:
+ case 181 /* ImportType */:
+ case 212 /* MetaProperty */:
node = parent;
break;
default:
@@ -90734,7 +91534,7 @@ var ts;
//
// If the tagname is a property access expression, we will then walk up to the top most of property access expression.
// Then, try to get a JSX container and its associated attributes type.
- if (parent && parent.kind === 185 /* PropertyAccessExpression */) {
+ if (parent && parent.kind === 187 /* PropertyAccessExpression */) {
contextToken = parent;
parent = parent.parent;
}
@@ -90742,39 +91542,38 @@ var ts;
if (currentToken.parent === location) {
switch (currentToken.kind) {
case 29 /* GreaterThanToken */:
- if (currentToken.parent.kind === 255 /* JsxElement */ || currentToken.parent.kind === 257 /* JsxOpeningElement */) {
+ if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) {
location = currentToken;
}
break;
case 41 /* SlashToken */:
- if (currentToken.parent.kind === 256 /* JsxSelfClosingElement */) {
+ if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) {
location = currentToken;
}
break;
}
}
switch (parent.kind) {
- case 258 /* JsxClosingElement */:
+ case 261 /* JsxClosingElement */:
if (contextToken.kind === 41 /* SlashToken */) {
isStartingCloseTag = true;
location = contextToken;
}
break;
- case 200 /* BinaryExpression */:
- if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) {
- // It has a left-hand side, so we're not in an opening JSX tag.
+ case 202 /* BinaryExpression */:
+ if (!binaryExpressionMayBeOpenTag(parent)) {
break;
}
// falls through
- case 256 /* JsxSelfClosingElement */:
- case 255 /* JsxElement */:
- case 257 /* JsxOpeningElement */:
+ case 259 /* JsxSelfClosingElement */:
+ case 258 /* JsxElement */:
+ case 260 /* JsxOpeningElement */:
if (contextToken.kind === 27 /* LessThanToken */) {
isRightOfOpenTag = true;
location = contextToken;
}
break;
- case 262 /* JsxAttribute */:
+ case 265 /* JsxAttribute */:
switch (previousToken.kind) {
case 58 /* EqualsToken */:
isJsxInitializer = true;
@@ -90827,11 +91626,11 @@ var ts;
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 };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 293 /* JSDocParameterTag */:
- case 299 /* JSDocPropertyTag */:
- case 294 /* JSDocReturnTag */:
- case 296 /* JSDocTypeTag */:
- case 298 /* JSDocTypedefTag */:
+ case 296 /* JSDocParameterTag */:
+ case 302 /* JSDocPropertyTag */:
+ case 297 /* JSDocReturnTag */:
+ case 299 /* JSDocTypeTag */:
+ case 301 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -90865,7 +91664,7 @@ var ts;
}
}
// 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 !== 274 /* SourceFile */ && d.kind !== 239 /* ModuleDeclaration */ && d.kind !== 238 /* EnumDeclaration */; })) {
+ if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 277 /* SourceFile */ && d.kind !== 242 /* ModuleDeclaration */ && d.kind !== 241 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -90889,27 +91688,31 @@ var ts;
// each individual type has. This is because we're going to add all identifiers
// anyways. So we might as well elevate the members that were at least part
// of the individual types to a higher status since we know what they are.
- symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker, /*isForAccess*/ true));
+ symbols.push.apply(symbols, getPropertiesForCompletion(type, typeChecker));
}
else {
for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) {
var symbol = _a[_i];
- if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 179 /* ImportType */ ? node : node.parent, type, symbol)) {
+ if (typeChecker.isValidPropertyAccessForCompletions(node.kind === 181 /* ImportType */ ? node : node.parent, type, symbol)) {
addPropertySymbol(symbol);
}
}
}
}
function addPropertySymbol(symbol) {
+ // For a computed property with an accessible name like `Symbol.iterator`,
+ // we'll add a completion for the *name* `Symbol` instead of for the property.
// If this is e.g. [Symbol.iterator], add a completion for `Symbol`.
- var symbolSymbol = ts.firstDefined(symbol.declarations, function (decl) {
- var name = ts.getNameOfDeclaration(decl);
- var leftName = name.kind === 147 /* ComputedPropertyName */ ? getLeftMostName(name.expression) : undefined;
- return leftName && typeChecker.getSymbolAtLocation(leftName);
- });
- if (symbolSymbol) {
- symbols.push(symbolSymbol);
- symbolToOriginInfoMap[ts.getSymbolId(symbolSymbol)] = { type: "symbol-member" };
+ var computedPropertyName = ts.firstDefined(symbol.declarations, function (decl) { return ts.tryCast(ts.getNameOfDeclaration(decl), ts.isComputedPropertyName); });
+ if (computedPropertyName) {
+ var leftMostName = getLeftMostName(computedPropertyName.expression); // The completion is for `Symbol`, not `iterator`.
+ var nameSymbol = leftMostName && typeChecker.getSymbolAtLocation(leftMostName);
+ // If this is nested like for `namespace N { export const sym = Symbol(); }`, we'll add the completion for `N`.
+ var firstAccessibleSymbol = nameSymbol && getFirstSymbolInChain(nameSymbol, contextToken, typeChecker);
+ if (firstAccessibleSymbol && !symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)]) {
+ symbols.push(firstAccessibleSymbol);
+ symbolToOriginInfoMap[ts.getSymbolId(firstAccessibleSymbol)] = { type: "symbol-member" };
+ }
}
else {
symbols.push(symbol);
@@ -90993,10 +91796,10 @@ var ts;
var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 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 !== 274 /* SourceFile */) {
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) {
var thisType = typeChecker.tryGetThisTypeAt(scopeNode);
if (thisType) {
- for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
var symbol = _a[_i];
symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" };
symbols.push(symbol);
@@ -91029,10 +91832,10 @@ var ts;
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 274 /* SourceFile */:
- case 202 /* TemplateExpression */:
- case 265 /* JsxExpression */:
- case 213 /* Block */:
+ case 277 /* SourceFile */:
+ case 204 /* TemplateExpression */:
+ case 268 /* JsxExpression */:
+ case 216 /* Block */:
return true;
default:
return ts.isStatement(scopeNode);
@@ -91079,12 +91882,12 @@ var ts;
return parentKind === 152 /* PropertyDeclaration */ ||
parentKind === 151 /* PropertySignature */ ||
parentKind === 149 /* Parameter */ ||
- parentKind === 232 /* VariableDeclaration */ ||
+ parentKind === 235 /* VariableDeclaration */ ||
ts.isFunctionLikeKind(parentKind);
case 58 /* EqualsToken */:
- return parentKind === 237 /* TypeAliasDeclaration */;
+ return parentKind === 240 /* TypeAliasDeclaration */;
case 118 /* AsKeyword */:
- return parentKind === 208 /* AsExpression */;
+ return parentKind === 210 /* AsExpression */;
}
}
return false;
@@ -91187,11 +91990,11 @@ var ts;
return true;
}
if (contextToken.kind === 29 /* GreaterThanToken */ && contextToken.parent) {
- if (contextToken.parent.kind === 257 /* JsxOpeningElement */) {
+ if (contextToken.parent.kind === 260 /* JsxOpeningElement */) {
return true;
}
- if (contextToken.parent.kind === 258 /* JsxClosingElement */ || contextToken.parent.kind === 256 /* JsxSelfClosingElement */) {
- return !!contextToken.parent.parent && contextToken.parent.parent.kind === 255 /* JsxElement */;
+ if (contextToken.parent.kind === 261 /* JsxClosingElement */ || contextToken.parent.kind === 259 /* JsxSelfClosingElement */) {
+ return !!contextToken.parent.parent && contextToken.parent.parent.kind === 258 /* JsxElement */;
}
}
return false;
@@ -91201,36 +92004,36 @@ var ts;
var containingNodeKind = previousToken.parent.kind;
switch (previousToken.kind) {
case 26 /* CommaToken */:
- return containingNodeKind === 187 /* CallExpression */ // func( a, |
+ return containingNodeKind === 189 /* CallExpression */ // func( a, |
|| containingNodeKind === 155 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
- || containingNodeKind === 188 /* NewExpression */ // new C(a, |
- || containingNodeKind === 183 /* ArrayLiteralExpression */ // [a, |
- || containingNodeKind === 200 /* BinaryExpression */ // const x = (a, |
+ || containingNodeKind === 190 /* NewExpression */ // new C(a, |
+ || containingNodeKind === 185 /* ArrayLiteralExpression */ // [a, |
+ || containingNodeKind === 202 /* BinaryExpression */ // const x = (a, |
|| containingNodeKind === 163 /* FunctionType */; // var x: (s: string, list|
case 19 /* OpenParenToken */:
- return containingNodeKind === 187 /* CallExpression */ // func( |
+ return containingNodeKind === 189 /* CallExpression */ // func( |
|| containingNodeKind === 155 /* Constructor */ // constructor( |
- || containingNodeKind === 188 /* NewExpression */ // new C(a|
- || containingNodeKind === 191 /* ParenthesizedExpression */ // const x = (a|
- || containingNodeKind === 173 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
+ || containingNodeKind === 190 /* NewExpression */ // new C(a|
+ || containingNodeKind === 193 /* ParenthesizedExpression */ // const x = (a|
+ || containingNodeKind === 175 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
case 21 /* OpenBracketToken */:
- return containingNodeKind === 183 /* ArrayLiteralExpression */ // [ |
+ return containingNodeKind === 185 /* ArrayLiteralExpression */ // [ |
|| containingNodeKind === 160 /* IndexSignature */ // [ | : string ]
|| containingNodeKind === 147 /* ComputedPropertyName */; // [ | /* this can become an index signature */
case 129 /* ModuleKeyword */: // module |
case 130 /* NamespaceKeyword */: // namespace |
return true;
case 23 /* DotToken */:
- return containingNodeKind === 239 /* ModuleDeclaration */; // module A.|
+ return containingNodeKind === 242 /* ModuleDeclaration */; // module A.|
case 17 /* OpenBraceToken */:
- return containingNodeKind === 235 /* ClassDeclaration */; // class A{ |
+ return containingNodeKind === 238 /* ClassDeclaration */; // class A{ |
case 58 /* EqualsToken */:
- return containingNodeKind === 232 /* VariableDeclaration */ // const x = a|
- || containingNodeKind === 200 /* BinaryExpression */; // x = a|
+ return containingNodeKind === 235 /* VariableDeclaration */ // const x = a|
+ || containingNodeKind === 202 /* BinaryExpression */; // x = a|
case 14 /* TemplateHead */:
- return containingNodeKind === 202 /* TemplateExpression */; // `aa ${|
+ return containingNodeKind === 204 /* TemplateExpression */; // `aa ${|
case 15 /* TemplateMiddle */:
- return containingNodeKind === 211 /* TemplateSpan */; // `aa ${10} dd ${|
+ return containingNodeKind === 214 /* TemplateSpan */; // `aa ${10} dd ${|
case 114 /* PublicKeyword */:
case 112 /* PrivateKeyword */:
case 113 /* ProtectedKeyword */:
@@ -91268,16 +92071,16 @@ var ts;
completionKind = 0 /* ObjectPropertyDeclaration */;
var typeMembers;
var existingMembers;
- if (objectLikeContainer.kind === 184 /* ObjectLiteralExpression */) {
+ if (objectLikeContainer.kind === 186 /* ObjectLiteralExpression */) {
var typeForObject = typeChecker.getContextualType(objectLikeContainer);
if (!typeForObject)
return 2 /* Fail */;
isNewIdentifierLocation = hasIndexSignature(typeForObject);
- typeMembers = getPropertiesForCompletion(typeForObject, typeChecker, /*isForAccess*/ false);
+ typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker);
existingMembers = objectLikeContainer.properties;
}
else {
- ts.Debug.assert(objectLikeContainer.kind === 180 /* ObjectBindingPattern */);
+ ts.Debug.assert(objectLikeContainer.kind === 182 /* ObjectBindingPattern */);
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
@@ -91288,7 +92091,7 @@ var ts;
// through type declaration or inference.
// Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed -
// type of parameter will flow in from the contextual type of the function
- var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 222 /* ForOfStatement */;
+ var canGetType = ts.hasInitializer(rootDeclaration) || ts.hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === 225 /* ForOfStatement */;
if (!canGetType && rootDeclaration.kind === 149 /* Parameter */) {
if (ts.isExpression(rootDeclaration.parent)) {
canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
@@ -91335,7 +92138,7 @@ var ts;
return 0 /* Continue */;
// cursor is in an import clause
// try to show exported member for imported module
- var moduleSpecifier = (namedImportsOrExports.kind === 247 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier;
+ var moduleSpecifier = (namedImportsOrExports.kind === 250 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier;
var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217
if (!moduleSpecifierSymbol)
return 2 /* Fail */;
@@ -91379,8 +92182,8 @@ var ts;
if (!(classElementModifierFlags & 8 /* Private */)) {
// List of property symbols of base type that are not private and already implemented
var baseSymbols = ts.flatMap(ts.getAllSuperTypeNodes(decl), function (baseTypeNode) {
- var type = typeChecker.getTypeAtLocation(baseTypeNode); // TODO: GH#18217
- return typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type);
+ var type = typeChecker.getTypeAtLocation(baseTypeNode);
+ return type && typeChecker.getPropertiesOfType(classElementModifierFlags & 32 /* Static */ ? typeChecker.getTypeOfSymbolAtLocation(type.symbol, decl) : type);
});
symbols = filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags);
}
@@ -91450,14 +92253,14 @@ var ts;
case 28 /* LessThanSlashToken */:
case 41 /* SlashToken */:
case 71 /* Identifier */:
- case 185 /* PropertyAccessExpression */:
- case 263 /* JsxAttributes */:
- case 262 /* JsxAttribute */:
- case 264 /* JsxSpreadAttribute */:
- if (parent && (parent.kind === 256 /* JsxSelfClosingElement */ || parent.kind === 257 /* JsxOpeningElement */)) {
+ case 187 /* PropertyAccessExpression */:
+ case 266 /* JsxAttributes */:
+ case 265 /* JsxAttribute */:
+ case 267 /* JsxSpreadAttribute */:
+ if (parent && (parent.kind === 259 /* JsxSelfClosingElement */ || parent.kind === 260 /* JsxOpeningElement */)) {
return parent;
}
- else if (parent.kind === 262 /* JsxAttribute */) {
+ else if (parent.kind === 265 /* JsxAttribute */) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
@@ -91469,7 +92272,7 @@ var ts;
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
case 9 /* StringLiteral */:
- if (parent && ((parent.kind === 262 /* JsxAttribute */) || (parent.kind === 264 /* JsxSpreadAttribute */))) {
+ if (parent && ((parent.kind === 265 /* JsxAttribute */) || (parent.kind === 267 /* JsxSpreadAttribute */))) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
@@ -91479,8 +92282,8 @@ var ts;
break;
case 18 /* CloseBraceToken */:
if (parent &&
- parent.kind === 265 /* JsxExpression */ &&
- parent.parent && parent.parent.kind === 262 /* JsxAttribute */) {
+ parent.kind === 268 /* JsxExpression */ &&
+ parent.parent && parent.parent.kind === 265 /* JsxAttribute */) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
@@ -91488,7 +92291,7 @@ var ts;
// each JsxAttribute can have initializer as JsxExpression
return parent.parent.parent.parent;
}
- if (parent && parent.kind === 264 /* JsxSpreadAttribute */) {
+ if (parent && parent.kind === 267 /* JsxSpreadAttribute */) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
@@ -91508,49 +92311,49 @@ var ts;
var containingNodeKind = parent.kind;
switch (contextToken.kind) {
case 26 /* CommaToken */:
- return containingNodeKind === 232 /* VariableDeclaration */ ||
- containingNodeKind === 233 /* VariableDeclarationList */ ||
- containingNodeKind === 214 /* VariableStatement */ ||
- containingNodeKind === 238 /* EnumDeclaration */ || // enum a { foo, |
+ return containingNodeKind === 235 /* VariableDeclaration */ ||
+ containingNodeKind === 236 /* VariableDeclarationList */ ||
+ containingNodeKind === 217 /* VariableStatement */ ||
+ containingNodeKind === 241 /* EnumDeclaration */ || // enum a { foo, |
isFunctionLikeButNotConstructor(containingNodeKind) ||
- containingNodeKind === 236 /* InterfaceDeclaration */ || // interface A
= contextToken.pos);
case 23 /* DotToken */:
- return containingNodeKind === 181 /* ArrayBindingPattern */; // var [.|
+ return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.|
case 56 /* ColonToken */:
- return containingNodeKind === 182 /* BindingElement */; // var {x :html|
+ return containingNodeKind === 184 /* BindingElement */; // var {x :html|
case 21 /* OpenBracketToken */:
- return containingNodeKind === 181 /* ArrayBindingPattern */; // var [x|
+ return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x|
case 19 /* OpenParenToken */:
- return containingNodeKind === 269 /* CatchClause */ ||
+ return containingNodeKind === 272 /* CatchClause */ ||
isFunctionLikeButNotConstructor(containingNodeKind);
case 17 /* OpenBraceToken */:
- return containingNodeKind === 238 /* EnumDeclaration */; // enum a { |
+ return containingNodeKind === 241 /* EnumDeclaration */; // enum a { |
case 27 /* LessThanToken */:
- return containingNodeKind === 235 /* ClassDeclaration */ || // class A< |
- containingNodeKind === 205 /* ClassExpression */ || // var C = class D< |
- containingNodeKind === 236 /* InterfaceDeclaration */ || // interface A< |
- containingNodeKind === 237 /* TypeAliasDeclaration */ || // type List< |
+ return containingNodeKind === 238 /* ClassDeclaration */ || // class A< |
+ containingNodeKind === 207 /* ClassExpression */ || // var C = class D< |
+ containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< |
+ containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< |
ts.isFunctionLikeKind(containingNodeKind);
case 115 /* StaticKeyword */:
return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent);
case 24 /* DotDotDotToken */:
return containingNodeKind === 149 /* Parameter */ ||
- (!!parent.parent && parent.parent.kind === 181 /* ArrayBindingPattern */); // var [...z|
+ (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z|
case 114 /* PublicKeyword */:
case 112 /* PrivateKeyword */:
case 113 /* ProtectedKeyword */:
return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent);
case 118 /* AsKeyword */:
- return containingNodeKind === 248 /* ImportSpecifier */ ||
- containingNodeKind === 252 /* ExportSpecifier */ ||
- containingNodeKind === 246 /* NamespaceImport */;
+ return containingNodeKind === 251 /* ImportSpecifier */ ||
+ containingNodeKind === 255 /* ExportSpecifier */ ||
+ containingNodeKind === 249 /* NamespaceImport */;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
if (isFromObjectTypeDeclaration(contextToken)) {
@@ -91634,9 +92437,9 @@ var ts;
for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
var m = existingMembers_1[_i];
// Ignore omitted expressions for missing members
- if (m.kind !== 270 /* PropertyAssignment */ &&
- m.kind !== 271 /* ShorthandPropertyAssignment */ &&
- m.kind !== 182 /* BindingElement */ &&
+ if (m.kind !== 273 /* PropertyAssignment */ &&
+ m.kind !== 274 /* ShorthandPropertyAssignment */ &&
+ m.kind !== 184 /* BindingElement */ &&
m.kind !== 154 /* MethodDeclaration */ &&
m.kind !== 156 /* GetAccessor */ &&
m.kind !== 157 /* SetAccessor */) {
@@ -91658,7 +92461,7 @@ var ts;
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
var name = ts.getNameOfDeclaration(m);
- existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
+ existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
existingMemberNames.set(existingName, true); // TODO: GH#18217
}
@@ -91717,7 +92520,7 @@ var ts;
if (isCurrentlyEditingNode(attr)) {
continue;
}
- if (attr.kind === 262 /* JsxAttribute */) {
+ if (attr.kind === 265 /* JsxAttribute */) {
seenNames.set(attr.name.escapedText, true);
}
}
@@ -91824,47 +92627,28 @@ var ts;
}
/** Get the corresponding JSDocTag node if the position is in a jsDoc comment */
function getJsDocTagAtPosition(node, position) {
- var jsDoc = getJsDocHavingNode(node).jsDoc;
- if (!jsDoc)
- return undefined;
- for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) {
- var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags;
- if (!tags || position < pos || position > end)
- continue;
- for (var i = tags.length - 1; i >= 0; i--) {
- var tag = tags[i];
- if (position >= tag.pos) {
- return tag;
- }
- }
- }
+ var jsdoc = ts.findAncestor(node, ts.isJSDoc);
+ return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined);
}
- function getJsDocHavingNode(node) {
- if (!ts.isToken(node))
- return node;
- switch (node.kind) {
- case 104 /* VarKeyword */:
- case 110 /* LetKeyword */:
- case 76 /* ConstKeyword */:
- // if the current token is var, let or const, skip the VariableDeclarationList
- return node.parent.parent;
- default:
- return node.parent;
- }
+ function getPropertiesForObjectExpression(contextualType, obj, checker) {
+ return contextualType.isUnion()
+ ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) {
+ // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals.
+ return !(memberType.flags & 32764 /* Primitive */ ||
+ checker.isArrayLikeType(memberType) ||
+ ts.typeHasCallOrConstructSignatures(memberType, checker) ||
+ checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj));
+ }))
+ : contextualType.getApparentProperties();
}
/**
* Gets all properties on a type, but if that type is a union of several types,
* excludes array-like types or callable/constructable types.
*/
- function getPropertiesForCompletion(type, checker, isForAccess) {
- if (!(type.isUnion())) {
- return ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
- }
- // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals.
- var filteredTypes = isForAccess ? type.types : type.types.filter(function (memberType) {
- return !(memberType.flags & 32764 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker));
- });
- return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined");
+ function getPropertiesForCompletion(type, checker) {
+ return type.isUnion()
+ ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined")
+ : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined");
}
/**
* Returns the immediate owning class declaration of a context token,
@@ -91873,7 +92657,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 300 /* SyntaxList */:
+ case 303 /* 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);
@@ -91920,7 +92704,7 @@ var ts;
return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1;
case "<":
// Opening JSX tag
- return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 200 /* BinaryExpression */;
+ return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent));
case "/":
return ts.isStringLiteralLike(contextToken)
? !!ts.tryGetImportFromModuleSpecifier(contextToken)
@@ -91929,12 +92713,16 @@ var ts;
return ts.Debug.assertNever(triggerCharacter);
}
}
+ function binaryExpressionMayBeOpenTag(_a) {
+ var left = _a.left;
+ return ts.nodeIsMissing(left);
+ }
function isStringLiteralOrTemplate(node) {
switch (node.kind) {
case 9 /* StringLiteral */:
case 13 /* NoSubstitutionTemplateLiteral */:
- case 202 /* TemplateExpression */:
- case 189 /* TaggedTemplateExpression */:
+ case 204 /* TemplateExpression */:
+ case 191 /* TaggedTemplateExpression */:
return true;
default:
return false;
@@ -92068,7 +92856,7 @@ var ts;
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 274 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -92100,16 +92888,16 @@ var ts;
function getBreakOrContinueOwner(statement) {
return ts.findAncestor(statement, function (node) {
switch (node.kind) {
- case 227 /* SwitchStatement */:
- if (statement.kind === 223 /* ContinueStatement */) {
+ case 230 /* SwitchStatement */:
+ if (statement.kind === 226 /* ContinueStatement */) {
return false;
}
// falls through
- case 220 /* ForStatement */:
- case 221 /* ForInStatement */:
- case 222 /* ForOfStatement */:
- case 219 /* WhileStatement */:
- case 218 /* DoStatement */:
+ case 223 /* ForStatement */:
+ case 224 /* ForInStatement */:
+ case 225 /* ForOfStatement */:
+ case 222 /* WhileStatement */:
+ case 221 /* DoStatement */:
return !statement.label || isLabeledBy(node, statement.label.escapedText);
default:
// Don't cross function boundaries.
@@ -92119,24 +92907,17 @@ var ts;
});
}
function getModifierOccurrences(modifier, declaration) {
- var modifierFlag = ts.modifierToFlag(modifier);
- return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) {
- if (ts.getModifierFlags(node) & modifierFlag) {
- var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; });
- ts.Debug.assert(!!mod);
- return mod;
- }
- });
+ return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); });
}
function getNodesToSearchForModifier(declaration, modifierFlag) {
// Types of node whose children might have modifiers.
var container = declaration.parent;
switch (container.kind) {
- case 240 /* ModuleBlock */:
- case 274 /* SourceFile */:
- case 213 /* Block */:
- case 266 /* CaseClause */:
- case 267 /* DefaultClause */:
+ case 243 /* ModuleBlock */:
+ case 277 /* SourceFile */:
+ case 216 /* Block */:
+ case 269 /* CaseClause */:
+ case 270 /* DefaultClause */:
// Container is either a class declaration or the declaration is a classDeclaration
if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) {
return declaration.members.concat([declaration]);
@@ -92146,10 +92927,10 @@ var ts;
}
case 155 /* Constructor */:
case 154 /* MethodDeclaration */:
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : []));
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
var nodes = container.members;
// If we're an accessibility modifier, we're in an instance member and should search
// the constructor's parameter list for instance members as well.
@@ -92182,7 +92963,7 @@ var ts;
var keywords = [];
if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) {
// If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
- if (loopNode.kind === 218 /* DoStatement */) {
+ if (loopNode.kind === 221 /* DoStatement */) {
var loopTokens = loopNode.getChildren();
for (var i = loopTokens.length - 1; i >= 0; i--) {
if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) {
@@ -92202,13 +92983,13 @@ var ts;
var owner = getBreakOrContinueOwner(breakOrContinueStatement);
if (owner) {
switch (owner.kind) {
- case 220 /* ForStatement */:
- case 221 /* ForInStatement */:
- case 222 /* ForOfStatement */:
- case 218 /* DoStatement */:
- case 219 /* WhileStatement */:
+ case 223 /* ForStatement */:
+ case 224 /* ForInStatement */:
+ case 225 /* ForOfStatement */:
+ case 221 /* DoStatement */:
+ case 222 /* WhileStatement */:
return getLoopBreakContinueOccurrences(owner);
- case 227 /* SwitchStatement */:
+ case 230 /* SwitchStatement */:
return getSwitchCaseDefaultOccurrences(owner);
}
}
@@ -92580,12 +93361,13 @@ var ts;
if (!markSeenDirectImport(direct)) {
continue;
}
- cancellationToken.throwIfCancellationRequested();
+ if (cancellationToken)
+ cancellationToken.throwIfCancellationRequested();
switch (direct.kind) {
- case 187 /* CallExpression */:
+ case 189 /* CallExpression */:
if (!isAvailableThroughGlobal) {
var parent = direct.parent;
- if (exportKind === 2 /* ExportEquals */ && parent.kind === 232 /* VariableDeclaration */) {
+ if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) {
var name = parent.name;
if (name.kind === 71 /* Identifier */) {
directImports.push(name);
@@ -92598,20 +93380,20 @@ var ts;
break;
case 71 /* Identifier */: // for 'const x = require("y");
break; // TODO: GH#23879
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false);
break;
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
directImports.push(direct);
var namedBindings = direct.importClause && direct.importClause.namedBindings;
- if (namedBindings && namedBindings.kind === 246 /* NamespaceImport */) {
+ if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) {
handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true);
}
else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) {
addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports
}
break;
- case 250 /* ExportDeclaration */:
+ case 253 /* ExportDeclaration */:
if (!direct.exportClause) {
// This is `export * from "foo"`, so imports of this module may import the export too.
handleDirectImports(getContainingModuleSymbol(direct, checker));
@@ -92621,7 +93403,7 @@ var ts;
directImports.push(direct);
}
break;
- case 179 /* ImportType */:
+ case 181 /* ImportType */:
directImports.push(direct);
break;
default:
@@ -92638,7 +93420,7 @@ var ts;
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 274 /* SourceFile */ || sourceFileLike.kind === 239 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -92693,7 +93475,7 @@ var ts;
}
return { importSearches: importSearches, singleReferences: singleReferences };
function handleImport(decl) {
- if (decl.kind === 243 /* ImportEqualsDeclaration */) {
+ if (decl.kind === 246 /* ImportEqualsDeclaration */) {
if (isExternalModuleImportEquals(decl)) {
handleNamespaceImportLike(decl.name);
}
@@ -92703,7 +93485,7 @@ var ts;
handleNamespaceImportLike(decl);
return;
}
- if (decl.kind === 179 /* ImportType */) {
+ if (decl.kind === 181 /* ImportType */) {
if (decl.qualifier) {
if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) {
singleReferences.push(decl.qualifier);
@@ -92718,17 +93500,17 @@ var ts;
if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) {
return;
}
- if (decl.kind === 250 /* ExportDeclaration */) {
+ if (decl.kind === 253 /* ExportDeclaration */) {
searchForNamedImport(decl.exportClause);
return;
}
var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings;
if (namedBindings) {
switch (namedBindings.kind) {
- case 246 /* NamespaceImport */:
+ case 249 /* NamespaceImport */:
handleNamespaceImportLike(namedBindings.name);
break;
- case 247 /* NamedImports */:
+ case 250 /* NamedImports */:
// 'default' might be accessed as a named import `{ default as foo }`.
if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) {
searchForNamedImport(namedBindings);
@@ -92778,7 +93560,7 @@ var ts;
}
}
else {
- var localSymbol = element.kind === 252 /* ExportSpecifier */ && element.propertyName
+ var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName
? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
: checker.getSymbolAtLocation(name);
addSearch(name, localSymbol);
@@ -92807,7 +93589,7 @@ var ts;
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 274 /* SourceFile */) {
+ if (searchSourceFile.kind === 277 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -92837,7 +93619,8 @@ var ts;
var map = ts.createMap();
for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
var sourceFile = sourceFiles_2[_i];
- cancellationToken.throwIfCancellationRequested();
+ if (cancellationToken)
+ cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
if (moduleSymbol) {
@@ -92854,7 +93637,7 @@ var ts;
}
/** 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 === 274 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -92869,15 +93652,15 @@ var ts;
else {
forEachPossibleImportOrExportStatement(sourceFile, function (statement) {
switch (statement.kind) {
- case 250 /* ExportDeclaration */:
- case 244 /* ImportDeclaration */: {
+ case 253 /* ExportDeclaration */:
+ case 247 /* ImportDeclaration */: {
var decl = statement;
if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) {
action(decl, decl.moduleSpecifier);
}
break;
}
- case 243 /* ImportEqualsDeclaration */: {
+ case 246 /* ImportEqualsDeclaration */: {
var decl = statement;
if (isExternalModuleImportEquals(decl)) {
action(decl, decl.moduleReference.expression);
@@ -92901,7 +93684,7 @@ var ts;
var parent = node.parent;
var grandParent = parent.parent;
if (symbol.exportSymbol) {
- if (parent.kind === 185 /* PropertyAccessExpression */) {
+ if (parent.kind === 187 /* PropertyAccessExpression */) {
// When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use.
// So check that we are at the declaration.
return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent)
@@ -93023,10 +93806,10 @@ var ts;
// If a reference is a class expression, the exported node would be its parent.
// If a reference is a variable declaration, the exported node would be the variable statement.
function getExportNode(parent, node) {
- if (parent.kind === 232 /* VariableDeclaration */) {
+ if (parent.kind === 235 /* VariableDeclaration */) {
var p = parent;
return p.name !== node ? undefined :
- p.parent.kind === 269 /* CatchClause */ ? undefined : p.parent.parent.kind === 214 /* VariableStatement */ ? p.parent.parent : undefined;
+ p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined;
}
else {
return parent;
@@ -93035,15 +93818,15 @@ var ts;
function isNodeImport(node) {
var parent = node.parent;
switch (parent.kind) {
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return parent.name === node && isExternalModuleImportEquals(parent)
? { isNamedImport: false }
: undefined;
- case 248 /* ImportSpecifier */:
+ case 251 /* ImportSpecifier */:
// For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
return parent.propertyName ? undefined : { isNamedImport: true };
- case 245 /* ImportClause */:
- case 246 /* NamespaceImport */:
+ case 248 /* ImportClause */:
+ case 249 /* NamespaceImport */:
ts.Debug.assert(parent.name === node);
return { isNamedImport: false };
default:
@@ -93076,21 +93859,21 @@ var ts;
return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
}
function getSourceFileLikeForImportDeclaration(node) {
- if (node.kind === 187 /* CallExpression */) {
+ if (node.kind === 189 /* CallExpression */) {
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 274 /* SourceFile */) {
+ if (parent.kind === 277 /* SourceFile */) {
return parent;
}
- ts.Debug.assert(parent.kind === 240 /* ModuleBlock */);
+ ts.Debug.assert(parent.kind === 243 /* ModuleBlock */);
return ts.cast(parent.parent, isAmbientModuleDeclaration);
}
function isAmbientModuleDeclaration(node) {
- return node.kind === 239 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */;
+ return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */;
}
function isExternalModuleImportEquals(eq) {
- return eq.moduleReference.kind === 254 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */;
+ return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */;
}
})(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
})(ts || (ts = {}));
@@ -93125,13 +93908,13 @@ var ts;
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 274 /* SourceFile */) {
+ if (node.kind === 277 /* SourceFile */) {
return undefined;
}
var checker = program.getTypeChecker();
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
- if (node.parent.kind === 271 /* ShorthandPropertyAssignment */) {
+ if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) {
var result_1 = [];
FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
return result_1;
@@ -93147,8 +93930,7 @@ var ts;
return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true });
}
}
- function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) {
- var node = ts.getTouchingPropertyName(sourceFile, position);
+ function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) {
return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry);
}
FindAllReferences.findReferencedEntries = findReferencedEntries;
@@ -93235,13 +94017,13 @@ var ts;
if (symbol) {
return getDefinitionKindAndDisplayParts(symbol, checker, node);
}
- else if (node.kind === 184 /* ObjectLiteralExpression */) {
+ else if (node.kind === 186 /* ObjectLiteralExpression */) {
return {
kind: "interface" /* interfaceElement */,
displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)]
};
}
- else if (node.kind === 205 /* ClassExpression */) {
+ else if (node.kind === 207 /* ClassExpression */) {
return {
kind: "local class" /* localClassElement */,
displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)]
@@ -93354,10 +94136,10 @@ var ts;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 274 /* SourceFile */:
+ case 277 /* 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 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
if (sourceFilesSet.has(decl.getSourceFile().fileName)) {
references.push({ type: "node", node: decl.name });
}
@@ -93515,7 +94297,7 @@ var ts;
this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken);
return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename);
};
- /** @param allSearchSymbols set of additinal symbols for use by `includes`. */
+ /** @param allSearchSymbols set of additional symbols for use by `includes`. */
State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) {
if (searchOptions === void 0) { searchOptions = {}; }
// Note: if this is an external module symbol, the name doesn't include quotes.
@@ -93598,6 +94380,24 @@ var ts;
}
}
}
+ function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) {
+ var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken);
+ var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers;
+ for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) {
+ var importLocation = importSearches_2[_i][0];
+ cb(importLocation);
+ }
+ for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) {
+ var indirectUser = indirectUsers_2[_b];
+ for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) {
+ var node = _d[_c];
+ if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) {
+ cb(node);
+ }
+ }
+ }
+ }
+ Core.eachExportReference = eachExportReference;
function shouldAddSingleReference(singleRef, state) {
if (!hasMatchingMeaning(singleRef, state))
return false;
@@ -93630,9 +94430,9 @@ var ts;
: undefined;
}
function getObjectBindingElementWithoutPropertyName(symbol) {
- var bindingElement = ts.getDeclarationOfKind(symbol, 182 /* BindingElement */);
+ var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */);
if (bindingElement &&
- bindingElement.parent.kind === 180 /* ObjectBindingPattern */ &&
+ bindingElement.parent.kind === 182 /* ObjectBindingPattern */ &&
ts.isIdentifier(bindingElement.name) &&
!bindingElement.propertyName) {
return bindingElement;
@@ -93654,7 +94454,7 @@ var ts;
// If this is the symbol of a named function expression or named class expression,
// then named references are limited to its own scope.
var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration;
- if (valueDeclaration && (valueDeclaration.kind === 192 /* FunctionExpression */ || valueDeclaration.kind === 205 /* ClassExpression */)) {
+ if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) {
return valueDeclaration;
}
if (!declarations) {
@@ -93664,7 +94464,7 @@ var ts;
if (flags & (4 /* Property */ | 8192 /* Method */)) {
var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); });
if (privateDeclaration) {
- return ts.getAncestor(privateDeclaration, 235 /* ClassDeclaration */);
+ return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */);
}
// Else this is a public property and could be accessed from anywhere.
return undefined;
@@ -93693,7 +94493,7 @@ var ts;
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 274 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 277 /* 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;
@@ -93732,6 +94532,28 @@ var ts;
}
}
Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile;
+ function eachSignatureCall(signature, sourceFiles, checker, cb) {
+ if (!signature.name || !ts.isIdentifier(signature.name))
+ return;
+ var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_i];
+ for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
+ var name = _b[_a];
+ if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
+ continue;
+ var called = ts.climbPastPropertyAccess(name);
+ var call = called.parent;
+ if (!ts.isCallExpression(call) || call.expression !== called)
+ continue;
+ var referenceSymbol = checker.getSymbolAtLocation(name);
+ if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) {
+ cb(call);
+ }
+ }
+ }
+ }
+ Core.eachSignatureCall = eachSignatureCall;
function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) {
if (container === void 0) { container = sourceFile; }
return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); });
@@ -93956,6 +94778,7 @@ var ts;
function getReferenceForShorthandProperty(_a, search, state) {
var flags = _a.flags, valueDeclaration = _a.valueDeclaration;
var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
+ var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration);
/*
* Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
* has two meanings: property name and property value. Therefore when we do findAllReference at the position where
@@ -93963,8 +94786,8 @@ var ts;
* the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the
* position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
- if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) {
- addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state);
+ if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) {
+ addReference(name, shorthandValueSymbol, state);
}
}
function addReference(referenceLocation, relatedSymbol, state) {
@@ -94072,7 +94895,7 @@ var ts;
if (refNode.kind !== 71 /* Identifier */) {
return;
}
- if (refNode.parent.kind === 271 /* ShorthandPropertyAssignment */) {
+ if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) {
// Go ahead and dereference the shorthand assignment by going to its definition
getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference);
}
@@ -94092,7 +94915,7 @@ var ts;
}
else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) {
var body = typeHavingNode.body;
- if (body.kind === 213 /* Block */) {
+ if (body.kind === 216 /* Block */) {
ts.forEachReturnStatement(body, function (returnStatement) {
if (returnStatement.expression)
addIfImplementation(returnStatement.expression);
@@ -94120,13 +94943,13 @@ var ts;
*/
function isImplementationExpression(node) {
switch (node.kind) {
- case 191 /* ParenthesizedExpression */:
+ case 193 /* ParenthesizedExpression */:
return isImplementationExpression(node.expression);
- case 193 /* ArrowFunction */:
- case 192 /* FunctionExpression */:
- case 184 /* ObjectLiteralExpression */:
- case 205 /* ClassExpression */:
- case 183 /* ArrayLiteralExpression */:
+ case 195 /* ArrowFunction */:
+ case 194 /* FunctionExpression */:
+ case 186 /* ObjectLiteralExpression */:
+ case 207 /* ClassExpression */:
+ case 185 /* ArrayLiteralExpression */:
return true;
default:
return false;
@@ -94224,20 +95047,20 @@ var ts;
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 274 /* SourceFile */:
+ case 277 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode)) {
return undefined;
}
// falls through
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
break;
// Computed properties in classes are not handled here because references to this are illegal,
// so there is no point finding references to them.
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 274 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -94245,19 +95068,19 @@ var ts;
}
var container = ts.getThisContainer(node, /* includeArrowFunctions */ false);
switch (searchSpaceNode.kind) {
- case 192 /* FunctionExpression */:
- case 234 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
return searchSpaceNode.symbol === container.symbol;
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol;
- case 205 /* ClassExpression */:
- case 235 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 238 /* ClassDeclaration */:
// 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 274 /* SourceFile */:
- return container.kind === 274 /* SourceFile */ && !ts.isExternalModule(container);
+ case 277 /* SourceFile */:
+ return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -94459,16 +95282,17 @@ var ts;
});
}
ts.getEditsForFileRename = getEditsForFileRename;
+ // exported for tests
function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) {
var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath);
return function (path) {
- var canonicalPath = getCanonicalFileName(path);
- if (canonicalPath === canonicalOldPath)
+ if (getCanonicalFileName(path) === canonicalOldPath)
return newFileOrDirPath;
- var suffix = ts.tryRemoveDirectoryPrefix(canonicalPath, canonicalOldPath);
+ var suffix = ts.tryRemoveDirectoryPrefix(path, canonicalOldPath, getCanonicalFileName);
return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix;
};
}
+ ts.getPathUpdater = getPathUpdater;
function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) {
var configFile = program.getCompilerOptions().configFile;
if (!configFile)
@@ -94539,9 +95363,10 @@ var ts;
}
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) {
+ var allFiles = program.getSourceFiles();
var _loop_3 = function (sourceFile) {
- var newFromOld = oldToNew(sourceFile.fileName);
- var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.fileName;
+ var newFromOld = oldToNew(sourceFile.path);
+ var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
var oldFromNew = newToOld(sourceFile.fileName);
var oldImportFromPath = oldFromNew || sourceFile.fileName;
@@ -94554,19 +95379,23 @@ var ts;
var newAbsolute = oldToNew(oldAbsolute);
return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName));
}, function (importLiteral) {
+ var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
+ // No need to update if it's an ambient module^M
+ if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); }))
+ return undefined;
var toImport = oldFromNew !== undefined
// If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
// TODO:GH#18217
? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program)
- : getSourceFileToImport(importLiteral, sourceFile, program, host, oldToNew);
- // If neither the importing source file nor the imported file moved, do nothing.
- return toImport === undefined || !toImport.updated && !importingSourceFileMoved
- ? undefined
- : ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, preferences);
+ : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
+ // Need an update if the imported file moved, or the importing file moved and was using a relative path.
+ return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text)))
+ ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences)
+ : undefined;
});
};
- for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile = _a[_i];
+ for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
+ var sourceFile = allFiles_1[_i];
_loop_3(sourceFile);
}
}
@@ -94576,12 +95405,10 @@ var ts;
function combinePathsSafe(pathA, pathB) {
return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB));
}
- function getSourceFileToImport(importLiteral, importingSourceFile, program, host, oldToNew) {
- var symbol = program.getTypeChecker().getSymbolAtLocation(importLiteral);
- if (symbol) {
- if (symbol.declarations.some(function (d) { return ts.isAmbientModule(d); }))
- return undefined; // No need to update if it's an ambient module
- var oldFileName = ts.find(symbol.declarations, ts.isSourceFile).fileName;
+ function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) {
+ if (importedModuleSymbol) {
+ // `find` should succeed because we checked for ambient modules before calling this function.
+ var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName;
var newFileName = oldToNew(oldFileName);
return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true };
}
@@ -94657,7 +95484,8 @@ var ts;
return getDefinitionInfoForIndexSignatures(node, typeChecker);
}
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
- if (calledDeclaration) {
+ // Don't go to the component constructor definition for a JSX element, just go to the component definition.
+ if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) {
var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
// For a function, if this is the original function definition, return just sigInfo.
// If this is the original constructor definition, parent is the class.
@@ -94677,7 +95505,7 @@ var ts;
// go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition
// is performed at the location of property access, we would like to go to definition of the property in the short-hand
// assignment. This case and others are handled by the following code.
- if (node.parent.kind === 271 /* ShorthandPropertyAssignment */) {
+ if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) {
var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : [];
}
@@ -94726,7 +95554,7 @@ var ts;
*/
function symbolMatchesSignature(s, calledDeclaration) {
return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent ||
- ts.isVariableDeclaration(calledDeclaration.parent) && s === calledDeclaration.parent.symbol;
+ !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol;
}
function getReferenceAtPosition(sourceFile, position, program) {
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
@@ -94819,11 +95647,11 @@ var ts;
return true;
}
switch (declaration.kind) {
- case 245 /* ImportClause */:
- case 243 /* ImportEqualsDeclaration */:
+ case 248 /* ImportClause */:
+ case 246 /* ImportEqualsDeclaration */:
return true;
- case 248 /* ImportSpecifier */:
- return declaration.parent.kind === 247 /* NamedImports */;
+ case 251 /* ImportSpecifier */:
+ return declaration.parent.kind === 250 /* NamedImports */;
default:
return false;
}
@@ -94877,7 +95705,7 @@ var ts;
return createDefinitionInfo(decl, typeChecker, decl.symbol, decl);
}
function findReferenceInPosition(refs, pos) {
- return ts.find(refs, function (ref) { return ref.pos <= pos && pos <= ref.end; });
+ return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); });
}
GoToDefinition.findReferenceInPosition = findReferenceInPosition;
function getDefinitionInfoForFileReference(name, targetFileName) {
@@ -94982,11 +95810,11 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 293 /* JSDocParameterTag */:
- case 299 /* JSDocPropertyTag */:
+ case 296 /* JSDocParameterTag */:
+ case 302 /* JSDocPropertyTag */:
return [declaration];
- case 292 /* JSDocCallbackTag */:
- case 298 /* JSDocTypedefTag */:
+ case 295 /* JSDocCallbackTag */:
+ case 301 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -95007,16 +95835,16 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 290 /* JSDocAugmentsTag */:
+ case 293 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 297 /* JSDocTemplateTag */:
+ case 300 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 296 /* JSDocTypeTag */:
+ case 299 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 298 /* JSDocTypedefTag */:
- case 292 /* JSDocCallbackTag */:
- case 299 /* JSDocPropertyTag */:
- case 293 /* JSDocParameterTag */:
+ case 301 /* JSDocTypedefTag */:
+ case 295 /* JSDocCallbackTag */:
+ case 302 /* JSDocPropertyTag */:
+ case 296 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -95146,7 +95974,7 @@ var ts;
if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) {
return undefined;
}
- var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
+ var tokenAtPos = ts.getTokenAtPosition(sourceFile, position);
var tokenStart = tokenAtPos.getStart(sourceFile);
if (!tokenAtPos || tokenStart < position) {
return undefined;
@@ -95164,10 +95992,7 @@ var ts;
var singleLineResult = "/** */";
return { newText: singleLineResult, caretOffset: 3 };
}
- var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position);
- var lineStart = sourceFile.getLineStarts()[posLineAndChar.line];
- // replace non-whitespace characters in prefix with spaces.
- var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; });
+ var indentationStr = getIndentationStringAtPosition(sourceFile, position);
// A doc comment consists of the following
// * The opening comment line
// * the first line (without a param) for the object's untagged info (this is also where the caret ends up)
@@ -95175,8 +96000,7 @@ var ts;
// * TODO: other tags.
// * the closing comment line
// * if the caret was directly in front of the object, then we add an extra line and indentation.
- var preamble = "/**" + newLine +
- indentationStr + " * ";
+ var preamble = "/**" + newLine + indentationStr + " * ";
var result = preamble + newLine +
parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) +
indentationStr + " */" +
@@ -95184,6 +96008,14 @@ var ts;
return { newText: result, caretOffset: preamble.length };
}
JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition;
+ function getIndentationStringAtPosition(sourceFile, position) {
+ var text = sourceFile.text;
+ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
+ var pos = lineStart;
+ for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++)
+ ;
+ return text.slice(lineStart, pos);
+ }
function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) {
return parameters.map(function (_a, i) {
var name = _a.name, dotDotDotToken = _a.dotDotDotToken;
@@ -95195,20 +96027,21 @@ var ts;
function getCommentOwnerInfo(tokenAtPos) {
for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) {
switch (commentOwner.kind) {
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
case 154 /* MethodDeclaration */:
case 155 /* Constructor */:
case 153 /* MethodSignature */:
var parameters = commentOwner.parameters;
return { commentOwner: commentOwner, parameters: parameters };
- case 235 /* ClassDeclaration */:
- case 236 /* InterfaceDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 239 /* InterfaceDeclaration */:
case 151 /* PropertySignature */:
- case 238 /* EnumDeclaration */:
- case 273 /* EnumMember */:
- case 237 /* TypeAliasDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 276 /* EnumMember */:
+ case 240 /* TypeAliasDeclaration */:
return { commentOwner: commentOwner };
- case 214 /* VariableStatement */: {
+ case 217 /* VariableStatement */: {
var varStatement = commentOwner;
var varDeclarations = varStatement.declarationList.declarations;
var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer
@@ -95216,14 +96049,14 @@ var ts;
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 274 /* SourceFile */:
+ case 277 /* SourceFile */:
return undefined;
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
// then we must be somewhere within a dotted namespace name; however we don't
// want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
- return commentOwner.parent.kind === 239 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner };
- case 200 /* BinaryExpression */: {
+ return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner };
+ case 202 /* BinaryExpression */: {
var be = commentOwner;
if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) {
return undefined;
@@ -95243,14 +96076,14 @@ var ts;
* @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
*/
function getParametersFromRightHandSideOfAssignment(rightHandSide) {
- while (rightHandSide.kind === 191 /* ParenthesizedExpression */) {
+ while (rightHandSide.kind === 193 /* ParenthesizedExpression */) {
rightHandSide = rightHandSide.expression;
}
switch (rightHandSide.kind) {
- case 192 /* FunctionExpression */:
- case 193 /* ArrowFunction */:
+ case 194 /* FunctionExpression */:
+ case 195 /* ArrowFunction */:
return rightHandSide.parameters;
- case 205 /* ClassExpression */: {
+ case 207 /* ClassExpression */: {
var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration);
return ctr ? ctr.parameters : ts.emptyArray;
}
@@ -95279,15 +96112,12 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var sourceFile = sourceFiles_3[_i];
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
_loop_4(sourceFile);
}
rawItems.sort(compareNavigateToItems);
- if (maxResultCount !== undefined) {
- rawItems = rawItems.slice(0, maxResultCount);
- }
- return rawItems.map(createNavigateToItem);
+ return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
}
NavigateTo.getNavigateToItems = getNavigateToItems;
function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) {
@@ -95302,23 +96132,23 @@ var ts;
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
- var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); // TODO: GH#18217
+ // If the pattern has dots in it, then also see if the declaration container matches as well.
+ var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name);
if (fullMatch) {
rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration });
}
}
else {
- // If the pattern has dots in it, then also see if the declaration container matches as well.
rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration });
}
}
}
function shouldKeepItem(declaration, checker) {
switch (declaration.kind) {
- case 245 /* ImportClause */:
- case 248 /* ImportSpecifier */:
- case 243 /* ImportEqualsDeclaration */:
- var importer = checker.getSymbolAtLocation(declaration.name);
+ case 248 /* ImportClause */:
+ case 251 /* ImportSpecifier */:
+ case 246 /* ImportEqualsDeclaration */:
+ var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217
var imported = checker.getAliasedSymbol(importer);
return importer.escapedName !== imported.escapedName;
default:
@@ -95363,14 +96193,14 @@ var ts;
// First, if we started with a computed property name, then add all but the last
// portion into the container array.
var name = ts.getNameOfDeclaration(declaration);
- if (name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) {
- return undefined;
+ if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) {
+ return ts.emptyArray;
}
// Now, walk up our containers, adding all their names to the container array.
var container = ts.getContainerNode(declaration);
while (container) {
if (!tryAddSingleDeclarationName(container, containers)) {
- return undefined;
+ return ts.emptyArray;
}
container = ts.getContainerNode(container);
}
@@ -95395,7 +96225,7 @@ var ts;
textSpan: ts.createTextSpanFromNode(declaration),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: containerName ? containerName.text : "",
- containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ // TODO: GH#18217 Just use `container ? ...`
+ containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */,
};
}
})(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {}));
@@ -95556,19 +96386,19 @@ var ts;
addLeafNode(node);
}
break;
- case 245 /* ImportClause */:
+ case 248 /* ImportClause */:
var importClause = node;
// Handle default import case e.g.:
// import d from "mod";
if (importClause.name) {
- addLeafNode(importClause);
+ addLeafNode(importClause.name);
}
// Handle named bindings in imports e.g.:
// import * as NS from "mod";
// import {a, b as B} from "mod";
var namedBindings = importClause.namedBindings;
if (namedBindings) {
- if (namedBindings.kind === 246 /* NamespaceImport */) {
+ if (namedBindings.kind === 249 /* NamespaceImport */) {
addLeafNode(namedBindings);
}
else {
@@ -95579,8 +96409,8 @@ var ts;
}
}
break;
- case 182 /* BindingElement */:
- case 232 /* VariableDeclaration */:
+ case 184 /* BindingElement */:
+ case 235 /* VariableDeclaration */:
var _d = node, name = _d.name, initializer = _d.initializer;
if (ts.isBindingPattern(name)) {
addChildrenRecursively(name);
@@ -95601,12 +96431,12 @@ var ts;
addNodeWithRecursiveChild(node, initializer);
}
break;
- case 193 /* ArrowFunction */:
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
+ case 195 /* ArrowFunction */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
addNodeWithRecursiveChild(node, node.body);
break;
- case 238 /* EnumDeclaration */:
+ case 241 /* EnumDeclaration */:
startNode(node);
for (var _e = 0, _f = node.members; _e < _f.length; _e++) {
var member = _f[_e];
@@ -95616,9 +96446,9 @@ var ts;
}
endNode();
break;
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
- case 236 /* InterfaceDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 239 /* InterfaceDeclaration */:
startNode(node);
for (var _g = 0, _h = node.members; _g < _h.length; _g++) {
var member = _h[_g];
@@ -95626,18 +96456,18 @@ var ts;
}
endNode();
break;
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
addNodeWithRecursiveChild(node, getInteriorModule(node).body);
break;
- case 252 /* ExportSpecifier */:
- case 243 /* ImportEqualsDeclaration */:
+ case 255 /* ExportSpecifier */:
+ case 246 /* ImportEqualsDeclaration */:
case 160 /* IndexSignature */:
case 158 /* CallSignature */:
case 159 /* ConstructSignature */:
- case 237 /* TypeAliasDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
addLeafNode(node);
break;
- case 200 /* BinaryExpression */: {
+ case 202 /* BinaryExpression */: {
var special = ts.getSpecialPropertyAssignmentKind(node);
switch (special) {
case 1 /* ExportsProperty */:
@@ -95645,7 +96475,7 @@ var ts;
case 3 /* PrototypeProperty */:
case 6 /* Prototype */:
addNodeWithRecursiveChild(node, node.right);
- break;
+ return;
case 4 /* ThisProperty */:
case 5 /* Property */:
case 0 /* None */:
@@ -95721,7 +96551,7 @@ var ts;
case 156 /* GetAccessor */:
case 157 /* SetAccessor */:
return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */);
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
return areSameModule(a, b);
default:
return true;
@@ -95731,7 +96561,7 @@ var ts;
// Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'!
function areSameModule(a, b) {
// TODO: GH#18217
- return a.body.kind === b.body.kind && (a.body.kind !== 239 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
+ return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body));
}
/** Merge source into target. Source should be thrown away after this is called. */
function merge(target, source) {
@@ -95761,7 +96591,7 @@ var ts;
* So `new()` can still come before an `aardvark` method.
*/
function tryGetName(node) {
- if (node.kind === 239 /* ModuleDeclaration */) {
+ if (node.kind === 242 /* ModuleDeclaration */) {
return getModuleName(node);
}
var declName = ts.getNameOfDeclaration(node);
@@ -95769,16 +96599,16 @@ var ts;
return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217
}
switch (node.kind) {
- case 192 /* FunctionExpression */:
- case 193 /* ArrowFunction */:
- case 205 /* ClassExpression */:
+ case 194 /* FunctionExpression */:
+ case 195 /* ArrowFunction */:
+ case 207 /* ClassExpression */:
return getFunctionOrClassName(node);
default:
return undefined;
}
}
function getItemName(node, name) {
- if (node.kind === 239 /* ModuleDeclaration */) {
+ if (node.kind === 242 /* ModuleDeclaration */) {
return getModuleName(node);
}
if (name) {
@@ -95788,16 +96618,16 @@ var ts;
}
}
switch (node.kind) {
- case 274 /* SourceFile */:
+ case 277 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
: "";
- case 193 /* ArrowFunction */:
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
+ case 195 /* ArrowFunction */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
if (ts.getModifierFlags(node) & 512 /* Default */) {
return "default";
}
@@ -95835,25 +96665,25 @@ var ts;
return topLevel;
function isTopLevel(item) {
switch (navigationBarNodeKind(item)) {
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
- case 238 /* EnumDeclaration */:
- case 236 /* InterfaceDeclaration */:
- case 239 /* ModuleDeclaration */:
- case 274 /* SourceFile */:
- case 237 /* TypeAliasDeclaration */:
- case 298 /* JSDocTypedefTag */:
- case 292 /* JSDocCallbackTag */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 241 /* EnumDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ case 277 /* SourceFile */:
+ case 240 /* TypeAliasDeclaration */:
+ case 301 /* JSDocTypedefTag */:
+ case 295 /* JSDocCallbackTag */:
return true;
case 155 /* Constructor */:
case 154 /* MethodDeclaration */:
case 156 /* GetAccessor */:
case 157 /* SetAccessor */:
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
return hasSomeImportantChild(item);
- case 193 /* ArrowFunction */:
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
+ case 195 /* ArrowFunction */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
return isTopLevelFunctionDeclaration(item);
default:
return false;
@@ -95863,8 +96693,8 @@ var ts;
return false;
}
switch (navigationBarNodeKind(item.parent)) {
- case 240 /* ModuleBlock */:
- case 274 /* SourceFile */:
+ case 243 /* ModuleBlock */:
+ case 277 /* SourceFile */:
case 154 /* MethodDeclaration */:
case 155 /* Constructor */:
return true;
@@ -95875,7 +96705,7 @@ var ts;
function hasSomeImportantChild(item) {
return ts.some(item.children, function (child) {
var childKind = navigationBarNodeKind(child);
- return childKind !== 232 /* VariableDeclaration */ && childKind !== 182 /* BindingElement */;
+ return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */;
});
}
}
@@ -95932,7 +96762,7 @@ var ts;
// Otherwise, we need to aggregate each identifier to build up the qualified name.
var result = [];
result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
- while (moduleDeclaration.body && moduleDeclaration.body.kind === 239 /* ModuleDeclaration */) {
+ while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) {
moduleDeclaration = moduleDeclaration.body;
result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name));
}
@@ -95943,16 +96773,16 @@ var ts;
* We store 'A' as associated with a NavNode, and use getModuleName to traverse down again.
*/
function getInteriorModule(decl) {
- return decl.body.kind === 239 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217
+ return decl.body.kind === 242 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217
}
function isComputedProperty(member) {
return !member.name || member.name.kind === 147 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 274 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
- if (node.parent && node.parent.kind === 232 /* VariableDeclaration */) {
+ if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) {
node = node.parent;
}
return ts.getNodeModifiers(node);
@@ -95962,16 +96792,16 @@ var ts;
return ts.declarationNameToString(node.name);
}
// See if it is a var initializer. If so, use the var name.
- else if (node.parent.kind === 232 /* VariableDeclaration */) {
+ else if (node.parent.kind === 235 /* VariableDeclaration */) {
return ts.declarationNameToString(node.parent.name);
}
// See if it is of the form " = function(){...}". If so, use the text from the left-hand side.
- else if (node.parent.kind === 200 /* BinaryExpression */ &&
+ else if (node.parent.kind === 202 /* BinaryExpression */ &&
node.parent.operatorToken.kind === 58 /* EqualsToken */) {
return nodeText(node.parent.left).replace(whiteSpaceRegex, "");
}
// See if it is a property assignment, and if so use the property name
- else if (node.parent.kind === 270 /* PropertyAssignment */ && node.parent.name) {
+ else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) {
return nodeText(node.parent.name);
}
// Default exports are named "default"
@@ -95984,9 +96814,9 @@ var ts;
}
function isFunctionOrClassExpression(node) {
switch (node.kind) {
- case 193 /* ArrowFunction */:
- case 192 /* FunctionExpression */:
- case 205 /* ClassExpression */:
+ case 195 /* ArrowFunction */:
+ case 194 /* FunctionExpression */:
+ case 207 /* ClassExpression */:
return true;
default:
return false;
@@ -96042,10 +96872,7 @@ var ts;
});
// Delete or replace the first import.
if (newImportDecls.length === 0) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[0], {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
- });
+ changeTracker.delete(sourceFile, oldImportDecls[0]);
}
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
@@ -96057,7 +96884,7 @@ var ts;
}
// Delete any subsequent imports.
for (var i = 1; i < oldImportDecls.length; i++) {
- changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
+ changeTracker.delete(sourceFile, oldImportDecls[i]);
}
}
}
@@ -96353,7 +97180,7 @@ var ts;
var currentLineStart = lineStarts[i];
var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1;
var lineText = sourceFile.text.substring(currentLineStart, lineEnd);
- var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/);
+ var result = isRegionDelimiter(lineText);
if (!result || ts.isInComment(sourceFile, currentLineStart)) {
continue;
}
@@ -96371,6 +97198,10 @@ var ts;
}
}
}
+ var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/;
+ function isRegionDelimiter(lineText) {
+ return regionDelimiterRegExp.exec(lineText);
+ }
function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) {
var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
if (!comments)
@@ -96378,11 +97209,19 @@ var ts;
var firstSingleLineCommentStart = -1;
var lastSingleLineCommentEnd = -1;
var singleLineCommentCount = 0;
+ var sourceText = sourceFile.getFullText();
for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
cancellationToken.throwIfCancellationRequested();
switch (kind) {
case 2 /* SingleLineCommentTrivia */:
+ // never fold region delimiters into single-line comment regions
+ var commentText = sourceText.slice(pos, end);
+ if (isRegionDelimiter(commentText)) {
+ combineAndAddMultipleSingleLineComments();
+ singleLineCommentCount = 0;
+ break;
+ }
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (singleLineCommentCount === 0) {
@@ -96413,24 +97252,24 @@ var ts;
}
function getOutliningSpanForNode(n, sourceFile) {
switch (n.kind) {
- case 213 /* Block */:
+ case 216 /* Block */:
if (ts.isFunctionBlock(n)) {
- return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 193 /* ArrowFunction */);
+ return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */);
}
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collapse the block, but consider its hint span
// to be the entire span of the parent.
switch (n.parent.kind) {
- case 218 /* DoStatement */:
- case 221 /* ForInStatement */:
- case 222 /* ForOfStatement */:
- case 220 /* ForStatement */:
- case 217 /* IfStatement */:
- case 219 /* WhileStatement */:
- case 226 /* WithStatement */:
- case 269 /* CatchClause */:
+ case 221 /* DoStatement */:
+ case 224 /* ForInStatement */:
+ case 225 /* ForOfStatement */:
+ case 223 /* ForStatement */:
+ case 220 /* IfStatement */:
+ case 222 /* WhileStatement */:
+ case 229 /* WithStatement */:
+ case 272 /* CatchClause */:
return spanForNode(n.parent);
- case 230 /* TryStatement */:
+ case 233 /* TryStatement */:
// Could be the try-block, or the finally-block.
var tryStatement = n.parent;
if (tryStatement.tryBlock === n) {
@@ -96445,16 +97284,16 @@ var ts;
// the span of the block, independent of any parent span.
return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
}
- case 240 /* ModuleBlock */:
+ case 243 /* ModuleBlock */:
return spanForNode(n.parent);
- case 235 /* ClassDeclaration */:
- case 236 /* InterfaceDeclaration */:
- case 238 /* EnumDeclaration */:
- case 241 /* CaseBlock */:
+ case 238 /* ClassDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 244 /* CaseBlock */:
return spanForNode(n);
- case 184 /* ObjectLiteralExpression */:
+ case 186 /* ObjectLiteralExpression */:
return spanForObjectOrArrayLiteral(n);
- case 183 /* ArrayLiteralExpression */:
+ case 185 /* ArrayLiteralExpression */:
return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */);
}
function spanForObjectOrArrayLiteral(node, open) {
@@ -96528,7 +97367,6 @@ var ts;
if (!candidateMatch) {
return undefined;
}
- candidateContainers = candidateContainers || [];
// -1 because the last part was checked against the name, and only the rest
// of the parts are checked against the container.
if (dotSeparatedSegments.length - 1 > candidateContainers.length) {
@@ -97287,21 +98125,12 @@ var ts;
(function (ts) {
var Rename;
(function (Rename) {
- function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) {
- var getCanonicalDefaultLibName = ts.memoize(function () { return getCanonicalFileName(ts.normalizePath(defaultLibFileName)); });
+ function getRenameInfo(program, sourceFile, position) {
var node = ts.getTouchingPropertyName(sourceFile, position);
var renameInfo = node && nodeIsEligibleForRename(node)
- ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile)
+ ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); })
: undefined;
return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element);
- function isDefinedInLibraryFile(declaration) {
- if (!defaultLibFileName) {
- return false;
- }
- var sourceFile = declaration.getSourceFile();
- var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName));
- return canonicalName === getCanonicalDefaultLibName();
- }
}
Rename.getRenameInfo = getRenameInfo;
function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) {
@@ -97395,7 +98224,7 @@ var ts;
InvocationKind[InvocationKind["Call"] = 0] = "Call";
InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs";
})(InvocationKind || (InvocationKind = {}));
- function getSignatureHelpItems(program, sourceFile, position, cancellationToken) {
+ function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) {
var typeChecker = program.getTypeChecker();
// Decide whether to show signature help
var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position);
@@ -97403,6 +98232,12 @@ var ts;
// We are at the beginning of the file
return undefined;
}
+ if (shouldCarefullyCheckContext(triggerReason)) {
+ // In the middle of a string, don't provide signature help unless the user explicitly requested it.
+ if (ts.isInString(sourceFile, position, startingToken)) {
+ return undefined;
+ }
+ }
var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile);
if (!argumentInfo)
return undefined;
@@ -97421,6 +98256,10 @@ var ts;
return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); });
}
SignatureHelp.getSignatureHelpItems = getSignatureHelpItems;
+ function shouldCarefullyCheckContext(reason) {
+ // Only need to be careful if the user typed a character and signature help wasn't showing.
+ return !!reason && reason.kind === "characterTyped";
+ }
function getCandidateInfo(argumentInfo, checker) {
var invocation = argumentInfo.invocation;
if (invocation.kind === 0 /* Call */) {
@@ -97538,10 +98377,10 @@ var ts;
return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile);
}
}
- else if (ts.isTemplateHead(node) && parent.parent.kind === 189 /* TaggedTemplateExpression */) {
+ else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) {
var templateExpression = parent;
var tagExpression = templateExpression.parent;
- ts.Debug.assert(templateExpression.kind === 202 /* TemplateExpression */);
+ ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */);
var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
}
@@ -97690,7 +98529,7 @@ var ts;
// | |
// This is because a Missing node has no width. However, what we actually want is to include trivia
// leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail.
- if (template.kind === 202 /* TemplateExpression */) {
+ if (template.kind === 204 /* TemplateExpression */) {
var lastSpan = ts.last(template.templateSpans);
if (lastSpan.literal.getFullWidth() === 0) {
applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
@@ -97854,7 +98693,7 @@ var ts;
function check(node) {
if (isJsFile) {
switch (node.kind) {
- case 192 /* FunctionExpression */:
+ case 194 /* FunctionExpression */:
var decl = ts.getDeclarationOfJSInitializer(node);
if (decl) {
var symbol_2 = decl.symbol;
@@ -97864,7 +98703,7 @@ var ts;
}
}
// falls through if no diagnostic was created
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
var symbol = node.symbol;
if (symbol.members && (symbol.members.size > 0)) {
diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
@@ -97894,11 +98733,11 @@ var ts;
function containsTopLevelCommonjs(sourceFile) {
return sourceFile.statements.some(function (statement) {
switch (statement.kind) {
- case 214 /* VariableStatement */:
+ case 217 /* VariableStatement */:
return statement.declarationList.declarations.some(function (decl) {
return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
}); // TODO: GH#18217
- case 216 /* ExpressionStatement */: {
+ case 219 /* ExpressionStatement */: {
var expression = statement.expression;
if (!ts.isBinaryExpression(expression))
return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
@@ -97915,12 +98754,12 @@ var ts;
}
function importNameForConvertToDefaultImport(node) {
switch (node.kind) {
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier;
- return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 246 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
+ return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier)
? importClause.namedBindings.name
: undefined;
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return node.name;
default:
return undefined;
@@ -97943,7 +98782,7 @@ var ts;
}
var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol);
if (flags & 32 /* Class */) {
- return ts.getDeclarationOfKind(symbol, 205 /* ClassExpression */) ?
+ return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ?
"local class" /* localClassElement */ : "class" /* classElement */;
}
if (flags & 384 /* Enum */)
@@ -97988,7 +98827,7 @@ var ts;
if (ts.isFirstDeclarationOfSymbolParameter(symbol)) {
return "parameter" /* parameterElement */;
}
- else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) {
+ else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) {
return "const" /* constElement */;
}
else if (ts.forEach(symbol.declarations, ts.isLet)) {
@@ -98031,11 +98870,11 @@ var ts;
// If we requested completions after `x.` at the top-level, we may be at a source file location.
switch (location.parent && location.parent.kind) {
// If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'.
- case 257 /* JsxOpeningElement */:
- case 255 /* JsxElement */:
- case 256 /* JsxSelfClosingElement */:
+ case 260 /* JsxOpeningElement */:
+ case 258 /* JsxElement */:
+ case 259 /* JsxSelfClosingElement */:
return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */;
- case 262 /* JsxAttribute */:
+ case 265 /* JsxAttribute */:
return "JSX attribute" /* jsxAttribute */;
default:
return "property" /* memberVariableElement */;
@@ -98075,7 +98914,7 @@ var ts;
}
var signature = void 0;
type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location);
- if (location.parent && location.parent.kind === 185 /* PropertyAccessExpression */) {
+ if (location.parent && location.parent.kind === 187 /* PropertyAccessExpression */) {
var right = location.parent.name;
// Either the location is on the right of a property access, or on the left and the right is missing
if (right === location || (right && right.getFullWidth() === 0)) {
@@ -98096,7 +98935,7 @@ var ts;
if (callExpressionLike) {
var candidateSignatures = [];
signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217
- var useConstructSignatures = callExpressionLike.kind === 188 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */);
+ var useConstructSignatures = callExpressionLike.kind === 190 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */);
var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) {
// Get the first signature if there is one -- allSignatures may contain
@@ -98183,7 +99022,7 @@ var ts;
}
if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
addAliasPrefixIfNecessary();
- if (ts.getDeclarationOfKind(symbol, 205 /* ClassExpression */)) {
+ if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) {
// Special case for class expressions because we would like to indicate that
// the class name is local to the class body (similar to function expression)
// (local class) class
@@ -98217,7 +99056,7 @@ var ts;
}
if (symbolFlags & 384 /* Enum */) {
prefixNextMeaning();
- if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) {
+ if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) {
displayParts.push(ts.keywordPart(76 /* ConstKeyword */));
displayParts.push(ts.spacePart());
}
@@ -98227,7 +99066,7 @@ var ts;
}
if (symbolFlags & 1536 /* Module */) {
prefixNextMeaning();
- var declaration = ts.getDeclarationOfKind(symbol, 239 /* ModuleDeclaration */);
+ var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */);
var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */;
displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */));
displayParts.push(ts.spacePart());
@@ -98265,7 +99104,7 @@ var ts;
}
ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
}
- else if (declaration.kind === 237 /* TypeAliasDeclaration */) {
+ else if (declaration.kind === 240 /* TypeAliasDeclaration */) {
// Type alias type parameter
// For example
// type list = T[]; // Both T will go through same code path
@@ -98282,7 +99121,7 @@ var ts;
symbolKind = "enum member" /* enumMemberElement */;
addPrefixForAnyFunctionOrVar(symbol, "enum member");
var declaration = symbol.declarations[0];
- if (declaration.kind === 273 /* EnumMember */) {
+ if (declaration.kind === 276 /* EnumMember */) {
var constantValue = typeChecker.getConstantValue(declaration);
if (constantValue !== undefined) {
displayParts.push(ts.spacePart());
@@ -98312,17 +99151,17 @@ var ts;
}
}
switch (symbol.declarations[0].kind) {
- case 242 /* NamespaceExportDeclaration */:
+ case 245 /* NamespaceExportDeclaration */:
displayParts.push(ts.keywordPart(84 /* ExportKeyword */));
displayParts.push(ts.spacePart());
displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */));
break;
- case 249 /* ExportAssignment */:
+ case 252 /* ExportAssignment */:
displayParts.push(ts.keywordPart(84 /* ExportKeyword */));
displayParts.push(ts.spacePart());
displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */));
break;
- case 252 /* ExportSpecifier */:
+ case 255 /* ExportSpecifier */:
displayParts.push(ts.keywordPart(84 /* ExportKeyword */));
break;
default:
@@ -98331,7 +99170,7 @@ var ts;
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
ts.forEach(symbol.declarations, function (declaration) {
- if (declaration.kind === 243 /* ImportEqualsDeclaration */) {
+ if (declaration.kind === 246 /* ImportEqualsDeclaration */) {
var importEqualsDeclaration = declaration;
if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
displayParts.push(ts.spacePart());
@@ -98409,10 +99248,10 @@ var ts;
// 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 === 274 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- if (!declaration.parent || declaration.parent.kind !== 200 /* BinaryExpression */) {
+ if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) {
continue;
}
var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
@@ -98524,16 +99363,16 @@ var ts;
}
return ts.forEach(symbol.declarations, function (declaration) {
// Function expressions are local
- if (declaration.kind === 192 /* FunctionExpression */) {
+ if (declaration.kind === 194 /* FunctionExpression */) {
return true;
}
- if (declaration.kind !== 232 /* VariableDeclaration */ && declaration.kind !== 234 /* FunctionDeclaration */) {
+ if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) {
return false;
}
// 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 === 274 /* SourceFile */ || parent.kind === 240 /* ModuleBlock */) {
+ if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) {
return false;
}
}
@@ -98842,10 +99681,10 @@ var ts;
function shouldRescanJsxIdentifier(node) {
if (node.parent) {
switch (node.parent.kind) {
- case 262 /* JsxAttribute */:
- case 257 /* JsxOpeningElement */:
- case 258 /* JsxClosingElement */:
- case 256 /* JsxSelfClosingElement */:
+ case 265 /* JsxAttribute */:
+ case 260 /* JsxOpeningElement */:
+ case 261 /* JsxClosingElement */:
+ case 259 /* JsxSelfClosingElement */:
// May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier.
return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */;
}
@@ -99326,44 +100165,44 @@ var ts;
return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; };
}
function isForContext(context) {
- return context.contextNode.kind === 220 /* ForStatement */;
+ return context.contextNode.kind === 223 /* ForStatement */;
}
function isNotForContext(context) {
return !isForContext(context);
}
function isBinaryOpContext(context) {
switch (context.contextNode.kind) {
- case 200 /* BinaryExpression */:
- case 201 /* ConditionalExpression */:
- case 171 /* ConditionalType */:
- case 208 /* AsExpression */:
- case 252 /* ExportSpecifier */:
- case 248 /* ImportSpecifier */:
+ case 202 /* BinaryExpression */:
+ case 203 /* ConditionalExpression */:
+ case 173 /* ConditionalType */:
+ case 210 /* AsExpression */:
+ case 255 /* ExportSpecifier */:
+ case 251 /* ImportSpecifier */:
case 161 /* TypePredicate */:
- case 169 /* UnionType */:
- case 170 /* IntersectionType */:
+ case 171 /* UnionType */:
+ case 172 /* IntersectionType */:
return true;
// equals in binding elements: function foo([[x, y] = [1, 2]])
- case 182 /* BindingElement */:
+ case 184 /* BindingElement */:
// equals in type X = ...
- case 237 /* TypeAliasDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
// equal in import a = module('a');
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
// equal in let a = 0;
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
// equal in p = 0;
case 149 /* Parameter */:
- case 273 /* EnumMember */:
+ case 276 /* EnumMember */:
case 152 /* PropertyDeclaration */:
case 151 /* PropertySignature */:
return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */;
// "in" keyword in for (let x in []) { }
- case 221 /* ForInStatement */:
+ case 224 /* ForInStatement */:
// "in" keyword in [P in keyof T]: T[P]
case 148 /* TypeParameter */:
return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
- case 222 /* ForOfStatement */:
+ case 225 /* ForOfStatement */:
return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */;
}
return false;
@@ -99379,19 +100218,19 @@ var ts;
return contextKind === 152 /* PropertyDeclaration */ ||
contextKind === 151 /* PropertySignature */ ||
contextKind === 149 /* Parameter */ ||
- contextKind === 232 /* VariableDeclaration */ ||
+ contextKind === 235 /* VariableDeclaration */ ||
ts.isFunctionLikeKind(contextKind);
}
function isConditionalOperatorContext(context) {
- return context.contextNode.kind === 201 /* ConditionalExpression */ ||
- context.contextNode.kind === 171 /* ConditionalType */;
+ return context.contextNode.kind === 203 /* ConditionalExpression */ ||
+ context.contextNode.kind === 173 /* ConditionalType */;
}
function isSameLineTokenOrBeforeBlockContext(context) {
return context.TokensAreOnSameLine() || isBeforeBlockContext(context);
}
function isBraceWrappedContext(context) {
- return context.contextNode.kind === 180 /* ObjectBindingPattern */ ||
- context.contextNode.kind === 177 /* MappedType */ ||
+ return context.contextNode.kind === 182 /* ObjectBindingPattern */ ||
+ context.contextNode.kind === 179 /* MappedType */ ||
isSingleLineBlockContext(context);
}
// This check is done before an open brace in a control construct, a function, or a typescript block declaration
@@ -99417,17 +100256,17 @@ var ts;
return true;
}
switch (node.kind) {
- case 213 /* Block */:
- case 241 /* CaseBlock */:
- case 184 /* ObjectLiteralExpression */:
- case 240 /* ModuleBlock */:
+ case 216 /* Block */:
+ case 244 /* CaseBlock */:
+ case 186 /* ObjectLiteralExpression */:
+ case 243 /* ModuleBlock */:
return true;
}
return false;
}
function isFunctionDeclContext(context) {
switch (context.contextNode.kind) {
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
// case SyntaxKind.MemberFunctionDeclaration:
@@ -99435,13 +100274,13 @@ var ts;
case 157 /* SetAccessor */:
// case SyntaxKind.MethodSignature:
case 158 /* CallSignature */:
- case 192 /* FunctionExpression */:
+ case 194 /* FunctionExpression */:
case 155 /* Constructor */:
- case 193 /* ArrowFunction */:
+ case 195 /* ArrowFunction */:
// case SyntaxKind.ConstructorDeclaration:
// case SyntaxKind.SimpleArrowFunctionExpression:
// case SyntaxKind.ParenthesizedArrowFunctionExpression:
- case 236 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
+ case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one
return true;
}
return false;
@@ -99450,40 +100289,40 @@ var ts;
return !isFunctionDeclContext(context);
}
function isFunctionDeclarationOrFunctionExpressionContext(context) {
- return context.contextNode.kind === 234 /* FunctionDeclaration */ || context.contextNode.kind === 192 /* FunctionExpression */;
+ return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */;
}
function isTypeScriptDeclWithBlockContext(context) {
return nodeIsTypeScriptDeclWithBlockContext(context.contextNode);
}
function nodeIsTypeScriptDeclWithBlockContext(node) {
switch (node.kind) {
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
- case 236 /* InterfaceDeclaration */:
- case 238 /* EnumDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 239 /* InterfaceDeclaration */:
+ case 241 /* EnumDeclaration */:
case 166 /* TypeLiteral */:
- case 239 /* ModuleDeclaration */:
- case 250 /* ExportDeclaration */:
- case 251 /* NamedExports */:
- case 244 /* ImportDeclaration */:
- case 247 /* NamedImports */:
+ case 242 /* ModuleDeclaration */:
+ case 253 /* ExportDeclaration */:
+ case 254 /* NamedExports */:
+ case 247 /* ImportDeclaration */:
+ case 250 /* NamedImports */:
return true;
}
return false;
}
function isAfterCodeBlockContext(context) {
switch (context.currentTokenParent.kind) {
- case 235 /* ClassDeclaration */:
- case 239 /* ModuleDeclaration */:
- case 238 /* EnumDeclaration */:
- case 269 /* CatchClause */:
- case 240 /* ModuleBlock */:
- case 227 /* SwitchStatement */:
+ case 238 /* ClassDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 272 /* CatchClause */:
+ case 243 /* ModuleBlock */:
+ case 230 /* SwitchStatement */:
return true;
- case 213 /* Block */: {
+ case 216 /* Block */: {
var blockParent = context.currentTokenParent.parent;
// In a codefix scenario, we can't rely on parents being set. So just always return true.
- if (!blockParent || blockParent.kind !== 193 /* ArrowFunction */ && blockParent.kind !== 192 /* FunctionExpression */) {
+ if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) {
return true;
}
}
@@ -99492,31 +100331,31 @@ var ts;
}
function isControlDeclContext(context) {
switch (context.contextNode.kind) {
- case 217 /* IfStatement */:
- case 227 /* SwitchStatement */:
- case 220 /* ForStatement */:
- case 221 /* ForInStatement */:
- case 222 /* ForOfStatement */:
- case 219 /* WhileStatement */:
- case 230 /* TryStatement */:
- case 218 /* DoStatement */:
- case 226 /* WithStatement */:
+ case 220 /* IfStatement */:
+ case 230 /* SwitchStatement */:
+ case 223 /* ForStatement */:
+ case 224 /* ForInStatement */:
+ case 225 /* ForOfStatement */:
+ case 222 /* WhileStatement */:
+ case 233 /* TryStatement */:
+ case 221 /* DoStatement */:
+ case 229 /* WithStatement */:
// TODO
// case SyntaxKind.ElseClause:
- case 269 /* CatchClause */:
+ case 272 /* CatchClause */:
return true;
default:
return false;
}
}
function isObjectContext(context) {
- return context.contextNode.kind === 184 /* ObjectLiteralExpression */;
+ return context.contextNode.kind === 186 /* ObjectLiteralExpression */;
}
function isFunctionCallContext(context) {
- return context.contextNode.kind === 187 /* CallExpression */;
+ return context.contextNode.kind === 189 /* CallExpression */;
}
function isNewContext(context) {
- return context.contextNode.kind === 188 /* NewExpression */;
+ return context.contextNode.kind === 190 /* NewExpression */;
}
function isFunctionCallOrNewContext(context) {
return isFunctionCallContext(context) || isNewContext(context);
@@ -99528,28 +100367,28 @@ var ts;
return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */;
}
function isArrowFunctionContext(context) {
- return context.contextNode.kind === 193 /* ArrowFunction */;
+ return context.contextNode.kind === 195 /* ArrowFunction */;
}
function isImportTypeContext(context) {
- return context.contextNode.kind === 179 /* ImportType */;
+ return context.contextNode.kind === 181 /* ImportType */;
}
function isNonJsxSameLineTokenContext(context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}
function isNonJsxElementOrFragmentContext(context) {
- return context.contextNode.kind !== 255 /* JsxElement */ && context.contextNode.kind !== 259 /* JsxFragment */;
+ return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */;
}
function isJsxExpressionContext(context) {
- return context.contextNode.kind === 265 /* JsxExpression */ || context.contextNode.kind === 264 /* JsxSpreadAttribute */;
+ return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */;
}
function isNextTokenParentJsxAttribute(context) {
- return context.nextTokenParent.kind === 262 /* JsxAttribute */;
+ return context.nextTokenParent.kind === 265 /* JsxAttribute */;
}
function isJsxAttributeContext(context) {
- return context.contextNode.kind === 262 /* JsxAttribute */;
+ return context.contextNode.kind === 265 /* JsxAttribute */;
}
function isJsxSelfClosingElementContext(context) {
- return context.contextNode.kind === 256 /* JsxSelfClosingElement */;
+ return context.contextNode.kind === 259 /* JsxSelfClosingElement */;
}
function isNotBeforeBlockInFunctionDeclarationContext(context) {
return !isFunctionDeclContext(context) && !isBeforeBlockContext(context);
@@ -99567,14 +100406,14 @@ var ts;
return node.kind === 150 /* Decorator */;
}
function isStartOfVariableDeclarationList(context) {
- return context.currentTokenParent.kind === 233 /* VariableDeclarationList */ &&
+ return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ &&
context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
}
function isNotFormatOnEnter(context) {
return context.formattingRequestKind !== 2 /* FormatOnEnter */;
}
function isModuleDeclContext(context) {
- return context.contextNode.kind === 239 /* ModuleDeclaration */;
+ return context.contextNode.kind === 242 /* ModuleDeclaration */;
}
function isObjectTypeContext(context) {
return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
@@ -99588,21 +100427,21 @@ var ts;
}
switch (parent.kind) {
case 162 /* TypeReference */:
- case 190 /* TypeAssertionExpression */:
- case 237 /* TypeAliasDeclaration */:
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
- case 236 /* InterfaceDeclaration */:
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
- case 193 /* ArrowFunction */:
+ case 192 /* TypeAssertionExpression */:
+ case 240 /* TypeAliasDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 239 /* InterfaceDeclaration */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
+ case 195 /* ArrowFunction */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
case 158 /* CallSignature */:
case 159 /* ConstructSignature */:
- case 187 /* CallExpression */:
- case 188 /* NewExpression */:
- case 207 /* ExpressionWithTypeArguments */:
+ case 189 /* CallExpression */:
+ case 190 /* NewExpression */:
+ case 209 /* ExpressionWithTypeArguments */:
return true;
default:
return false;
@@ -99613,16 +100452,16 @@ var ts;
isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
}
function isTypeAssertionContext(context) {
- return context.contextNode.kind === 190 /* TypeAssertionExpression */;
+ return context.contextNode.kind === 192 /* TypeAssertionExpression */;
}
function isVoidOpContext(context) {
- return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 196 /* VoidExpression */;
+ return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */;
}
function isYieldOrYieldStarWithOperand(context) {
- return context.contextNode.kind === 203 /* YieldExpression */ && context.contextNode.expression !== undefined;
+ return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined;
}
function isNonNullAssertionContext(context) {
- return context.contextNode.kind === 209 /* NonNullExpression */;
+ return context.contextNode.kind === 211 /* NonNullExpression */;
}
})(formatting = ts.formatting || (ts.formatting = {}));
})(ts || (ts = {}));
@@ -99856,17 +100695,17 @@ var ts;
// i.e. parent is class declaration with the list of members and node is one of members.
function isListElement(parent, node) {
switch (parent.kind) {
- case 235 /* ClassDeclaration */:
- case 236 /* InterfaceDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 239 /* InterfaceDeclaration */:
return ts.rangeContainsRange(parent.members, node);
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
var body = parent.body;
- return !!body && body.kind === 240 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 274 /* SourceFile */:
- case 213 /* Block */:
- case 240 /* ModuleBlock */:
+ return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
+ case 277 /* SourceFile */:
+ case 216 /* Block */:
+ case 243 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
- case 269 /* CatchClause */:
+ case 272 /* CatchClause */:
return ts.rangeContainsRange(parent.block.statements, node);
}
return false;
@@ -100089,10 +100928,10 @@ var ts;
return node.modifiers[0].kind;
}
switch (node.kind) {
- case 235 /* ClassDeclaration */: return 75 /* ClassKeyword */;
- case 236 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */;
- case 234 /* FunctionDeclaration */: return 89 /* FunctionKeyword */;
- case 238 /* EnumDeclaration */: return 238 /* EnumDeclaration */;
+ case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */;
+ case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */;
+ case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */;
+ case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */;
case 156 /* GetAccessor */: return 125 /* GetKeyword */;
case 157 /* SetAccessor */: return 136 /* SetKeyword */;
case 154 /* MethodDeclaration */:
@@ -100102,7 +100941,10 @@ var ts;
// falls through
case 152 /* PropertyDeclaration */:
case 149 /* Parameter */:
- return ts.getNameOfDeclaration(node).kind;
+ var name = ts.getNameOfDeclaration(node);
+ if (name) {
+ return name.kind;
+ }
}
}
function getDynamicIndentation(node, nodeStartLine, indentation, delta) {
@@ -100146,15 +100988,15 @@ var ts;
case 41 /* SlashToken */:
case 29 /* GreaterThanToken */:
switch (container.kind) {
- case 257 /* JsxOpeningElement */:
- case 258 /* JsxClosingElement */:
- case 256 /* JsxSelfClosingElement */:
+ case 260 /* JsxOpeningElement */:
+ case 261 /* JsxClosingElement */:
+ case 259 /* JsxSelfClosingElement */:
return false;
}
break;
case 21 /* OpenBracketToken */:
case 22 /* CloseBracketToken */:
- if (container.kind !== 177 /* MappedType */) {
+ if (container.kind !== 179 /* MappedType */) {
return false;
}
break;
@@ -100254,7 +101096,7 @@ var ts;
indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false);
}
childContextNode = node;
- if (isFirstListItem && parent.kind === 183 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
+ if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
inheritedIndentation = childIndentation.indentation;
}
return inheritedIndentation;
@@ -100622,56 +101464,47 @@ var ts;
/**
* @param precedingToken pass `null` if preceding token was already computed and result was `undefined`.
*/
- function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword
- tokenAtPosition, predicate) {
- if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); }
+ function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword
+ tokenAtPosition) {
+ if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); }
+ var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc);
+ if (jsdoc)
+ tokenAtPosition = jsdoc.parent;
var tokenStart = tokenAtPosition.getStart(sourceFile);
if (tokenStart <= position && position < tokenAtPosition.getEnd()) {
return undefined;
}
- if (precedingToken === undefined) {
- precedingToken = ts.findPrecedingToken(position, sourceFile);
- }
+ precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken;
// Between two consecutive tokens, all comments are either trailing on the former
// or leading on the latter (and none are in both lists).
var trailingRangesOfPreviousToken = precedingToken && ts.getTrailingCommentRanges(sourceFile.text, precedingToken.end);
var leadingCommentRangesOfNextToken = ts.getLeadingCommentRangesOfNode(tokenAtPosition, sourceFile);
- var commentRanges = trailingRangesOfPreviousToken && leadingCommentRangesOfNextToken ?
- trailingRangesOfPreviousToken.concat(leadingCommentRangesOfNextToken) :
- trailingRangesOfPreviousToken || leadingCommentRangesOfNextToken;
- if (commentRanges) {
- for (var _i = 0, commentRanges_1 = commentRanges; _i < commentRanges_1.length; _i++) {
- var range = commentRanges_1[_i];
- // The end marker of a single-line comment does not include the newline character.
- // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
- //
- // // asdf ^\n
- //
- // But for closed multi-line comments, we don't want to be inside the comment in the following case:
- //
- // /* asdf */^
- //
- // However, unterminated multi-line comments *do* contain their end.
- //
- // Internally, we represent the end of the comment at the newline and closing '/', respectively.
- //
- if ((range.pos < position && position < range.end ||
- position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()))) {
- return (range.kind === 3 /* MultiLineCommentTrivia */ || !onlyMultiLine) && (!predicate || predicate(range)) ? range : undefined;
- }
- }
- }
- return undefined;
+ var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken);
+ return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) ||
+ // The end marker of a single-line comment does not include the newline character.
+ // With caret at `^`, in the following case, we are inside a comment (^ denotes the cursor position):
+ //
+ // // asdf ^\n
+ //
+ // But for closed multi-line comments, we don't want to be inside the comment in the following case:
+ //
+ // /* asdf */^
+ //
+ // However, unterminated multi-line comments *do* contain their end.
+ //
+ // Internally, we represent the end of the comment at the newline and closing '/', respectively.
+ //
+ position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); });
}
formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment;
function getOpenTokenForList(node, list) {
switch (node.kind) {
case 155 /* Constructor */:
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
- case 193 /* ArrowFunction */:
+ case 195 /* ArrowFunction */:
if (node.typeParameters === list) {
return 27 /* LessThanToken */;
}
@@ -100679,8 +101512,8 @@ var ts;
return 19 /* OpenParenToken */;
}
break;
- case 187 /* CallExpression */:
- case 188 /* NewExpression */:
+ case 189 /* CallExpression */:
+ case 190 /* NewExpression */:
if (node.typeArguments === list) {
return 27 /* LessThanToken */;
}
@@ -100785,9 +101618,9 @@ var ts;
if (options.indentStyle === ts.IndentStyle.None) {
return 0;
}
- var precedingToken = ts.findPrecedingToken(position, sourceFile);
- var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ true, precedingToken || null); // tslint:disable-line:no-null-keyword
- if (enclosingCommentRange) {
+ var precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true);
+ var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword
+ if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) {
return getCommentIndent(sourceFile, position, options, enclosingCommentRange);
}
if (!precedingToken) {
@@ -100805,7 +101638,7 @@ var ts;
if (options.indentStyle === ts.IndentStyle.Block) {
return getBlockIndent(sourceFile, position, options);
}
- if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 200 /* BinaryExpression */) {
+ if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) {
// previous token is comma that separates items in list - find the previous item and try to derive indentation from it
var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
if (actualIndentation !== -1 /* Unknown */) {
@@ -100961,7 +101794,7 @@ var ts;
// - 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 === 274 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -101009,7 +101842,7 @@ var ts;
}
SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled;
function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) {
- if (parent.kind === 217 /* IfStatement */ && parent.elseStatement === child) {
+ if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) {
var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile);
ts.Debug.assert(elseKeyword !== undefined);
var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
@@ -101027,13 +101860,13 @@ var ts;
switch (node.parent.kind) {
case 162 /* TypeReference */:
return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
- case 184 /* ObjectLiteralExpression */:
+ case 186 /* ObjectLiteralExpression */:
return node.parent.properties;
- case 183 /* ArrayLiteralExpression */:
+ case 185 /* ArrayLiteralExpression */:
return node.parent.elements;
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
- case 193 /* ArrowFunction */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
+ case 195 /* ArrowFunction */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
case 158 /* CallSignature */:
@@ -101044,21 +101877,21 @@ var ts;
return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
getListIfStartEndIsInListRange(node.parent.parameters, start, end);
}
- case 235 /* ClassDeclaration */:
+ case 238 /* ClassDeclaration */:
return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end);
- case 188 /* NewExpression */:
- case 187 /* CallExpression */: {
+ case 190 /* NewExpression */:
+ case 189 /* CallExpression */: {
var start = node.getStart(sourceFile);
return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
getListIfStartEndIsInListRange(node.parent.arguments, start, end);
}
- case 233 /* VariableDeclarationList */:
+ case 236 /* VariableDeclarationList */:
return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
- case 247 /* NamedImports */:
- case 251 /* NamedExports */:
+ case 250 /* NamedImports */:
+ case 254 /* NamedExports */:
return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
- case 180 /* ObjectBindingPattern */:
- case 181 /* ArrayBindingPattern */:
+ case 182 /* ObjectBindingPattern */:
+ case 183 /* ArrayBindingPattern */:
return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
}
}
@@ -101098,10 +101931,10 @@ var ts;
function getStartingExpression(node) {
while (true) {
switch (node.kind) {
- case 187 /* CallExpression */:
- case 188 /* NewExpression */:
- case 185 /* PropertyAccessExpression */:
- case 186 /* ElementAccessExpression */:
+ case 189 /* CallExpression */:
+ case 190 /* NewExpression */:
+ case 187 /* PropertyAccessExpression */:
+ case 188 /* ElementAccessExpression */:
node = node.expression;
break;
default:
@@ -101166,82 +101999,82 @@ var ts;
function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) {
var childKind = child ? child.kind : 0 /* Unknown */;
switch (parent.kind) {
- case 216 /* ExpressionStatement */:
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
- case 236 /* InterfaceDeclaration */:
- case 238 /* EnumDeclaration */:
- case 237 /* TypeAliasDeclaration */:
- case 183 /* ArrayLiteralExpression */:
- case 213 /* Block */:
- case 240 /* ModuleBlock */:
- case 184 /* ObjectLiteralExpression */:
+ case 219 /* ExpressionStatement */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 239 /* InterfaceDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 185 /* ArrayLiteralExpression */:
+ case 216 /* Block */:
+ case 243 /* ModuleBlock */:
+ case 186 /* ObjectLiteralExpression */:
case 166 /* TypeLiteral */:
- case 177 /* MappedType */:
+ case 179 /* MappedType */:
case 168 /* TupleType */:
- case 241 /* CaseBlock */:
- case 267 /* DefaultClause */:
- case 266 /* CaseClause */:
- case 191 /* ParenthesizedExpression */:
- case 185 /* PropertyAccessExpression */:
- case 187 /* CallExpression */:
- case 188 /* NewExpression */:
- case 214 /* VariableStatement */:
- case 249 /* ExportAssignment */:
- case 225 /* ReturnStatement */:
- case 201 /* ConditionalExpression */:
- case 181 /* ArrayBindingPattern */:
- case 180 /* ObjectBindingPattern */:
- case 257 /* JsxOpeningElement */:
- case 260 /* JsxOpeningFragment */:
- case 256 /* JsxSelfClosingElement */:
- case 265 /* JsxExpression */:
+ case 244 /* CaseBlock */:
+ case 270 /* DefaultClause */:
+ case 269 /* CaseClause */:
+ case 193 /* ParenthesizedExpression */:
+ case 187 /* PropertyAccessExpression */:
+ case 189 /* CallExpression */:
+ case 190 /* NewExpression */:
+ case 217 /* VariableStatement */:
+ case 252 /* ExportAssignment */:
+ case 228 /* ReturnStatement */:
+ case 203 /* ConditionalExpression */:
+ case 183 /* ArrayBindingPattern */:
+ case 182 /* ObjectBindingPattern */:
+ case 260 /* JsxOpeningElement */:
+ case 263 /* JsxOpeningFragment */:
+ case 259 /* JsxSelfClosingElement */:
+ case 268 /* JsxExpression */:
case 153 /* MethodSignature */:
case 158 /* CallSignature */:
case 159 /* ConstructSignature */:
case 149 /* Parameter */:
case 163 /* FunctionType */:
case 164 /* ConstructorType */:
- case 173 /* ParenthesizedType */:
- case 189 /* TaggedTemplateExpression */:
- case 197 /* AwaitExpression */:
- case 251 /* NamedExports */:
- case 247 /* NamedImports */:
- case 252 /* ExportSpecifier */:
- case 248 /* ImportSpecifier */:
+ case 175 /* ParenthesizedType */:
+ case 191 /* TaggedTemplateExpression */:
+ case 199 /* AwaitExpression */:
+ case 254 /* NamedExports */:
+ case 250 /* NamedImports */:
+ case 255 /* ExportSpecifier */:
+ case 251 /* ImportSpecifier */:
case 152 /* PropertyDeclaration */:
return true;
- case 232 /* VariableDeclaration */:
- case 270 /* PropertyAssignment */:
- if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 184 /* ObjectLiteralExpression */) { // TODO: GH#18217
+ case 235 /* VariableDeclaration */:
+ case 273 /* PropertyAssignment */:
+ if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217
return rangeIsOnOneLine(sourceFile, child);
}
return true;
- case 218 /* DoStatement */:
- case 219 /* WhileStatement */:
- case 221 /* ForInStatement */:
- case 222 /* ForOfStatement */:
- case 220 /* ForStatement */:
- case 217 /* IfStatement */:
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
+ case 221 /* DoStatement */:
+ case 222 /* WhileStatement */:
+ case 224 /* ForInStatement */:
+ case 225 /* ForOfStatement */:
+ case 223 /* ForStatement */:
+ case 220 /* IfStatement */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
case 154 /* MethodDeclaration */:
- case 193 /* ArrowFunction */:
+ case 195 /* ArrowFunction */:
case 155 /* Constructor */:
case 156 /* GetAccessor */:
case 157 /* SetAccessor */:
- return childKind !== 213 /* Block */;
- case 250 /* ExportDeclaration */:
- return childKind !== 251 /* NamedExports */;
- case 244 /* ImportDeclaration */:
- return childKind !== 245 /* ImportClause */ ||
- (!!child.namedBindings && child.namedBindings.kind !== 247 /* NamedImports */);
- case 255 /* JsxElement */:
- return childKind !== 258 /* JsxClosingElement */;
- case 259 /* JsxFragment */:
- return childKind !== 261 /* JsxClosingFragment */;
- case 170 /* IntersectionType */:
- case 169 /* UnionType */:
+ return childKind !== 216 /* Block */;
+ case 253 /* ExportDeclaration */:
+ return childKind !== 254 /* NamedExports */;
+ case 247 /* ImportDeclaration */:
+ return childKind !== 248 /* ImportClause */ ||
+ (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */);
+ case 258 /* JsxElement */:
+ return childKind !== 261 /* JsxClosingElement */;
+ case 262 /* JsxFragment */:
+ return childKind !== 264 /* JsxClosingFragment */;
+ case 172 /* IntersectionType */:
+ case 171 /* UnionType */:
if (childKind === 166 /* TypeLiteral */) {
return false;
}
@@ -101253,17 +102086,17 @@ var ts;
SmartIndenter.nodeWillIndentChild = nodeWillIndentChild;
function isControlFlowEndingStatement(kind, parent) {
switch (kind) {
- case 225 /* ReturnStatement */:
- case 229 /* ThrowStatement */: {
- if (parent.kind !== 213 /* Block */) {
+ case 228 /* ReturnStatement */:
+ case 232 /* ThrowStatement */: {
+ if (parent.kind !== 216 /* Block */) {
return true;
}
var grandParent = parent.parent;
// In a function, we may want to write inner functions after this.
- return !(grandParent && grandParent.kind === 192 /* FunctionExpression */ || grandParent.kind === 234 /* FunctionDeclaration */);
+ return !(grandParent && grandParent.kind === 194 /* FunctionExpression */ || grandParent.kind === 237 /* FunctionDeclaration */);
}
- case 223 /* ContinueStatement */:
- case 224 /* BreakStatement */:
+ case 226 /* ContinueStatement */:
+ case 227 /* BreakStatement */:
return true;
default:
return false;
@@ -101392,7 +102225,7 @@ var ts;
* Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element
*/
function isSeparator(node, candidate) {
- return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 184 /* ObjectLiteralExpression */));
+ return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */));
}
function spaces(count) {
var s = "";
@@ -101408,8 +102241,8 @@ var ts;
this.formatContext = formatContext;
this.changes = [];
this.newFiles = [];
- this.deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map
+ this.deletedNodes = [];
}
ChangeTracker.fromContext = function (context) {
return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
@@ -101423,13 +102256,11 @@ var ts;
this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range });
return this;
};
- /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
- ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
- var endPosition = getAdjustedEndPosition(sourceFile, node, options);
- this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- return this;
+ ChangeTracker.prototype.delete = function (sourceFile, node) {
+ this.deletedNodes.push({ sourceFile: sourceFile, node: node, });
+ };
+ ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) {
+ 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 = {}; }
@@ -101444,30 +102275,6 @@ var ts;
var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
- ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) {
- var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile);
- if (!containingList) {
- ts.Debug.fail("node is not a list element");
- return this;
- }
- var index = ts.indexOfNode(containingList, node);
- if (index < 0) {
- return this;
- }
- if (containingList.length === 1) {
- this.deleteNode(sourceFile, node);
- return this;
- }
- // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node.
- // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`.
- ts.Debug.assert(!this.deletedNodesInLists.has(node), "Deleting a node twice");
- this.deletedNodesInLists.add(node);
- this.deleteRange(sourceFile, {
- pos: startPositionToDeleteNodeInList(sourceFile, node),
- end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]),
- });
- return this;
- };
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
if (options === void 0) { options = {}; }
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
@@ -101533,7 +102340,7 @@ var ts;
// If so, we do not want to separate the node from its comment if we can.
// Otherwise, add an extra new line immediately before the error span.
var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
- var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false);
+ var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
var indent = sourceFile.text.slice(lineStartPosition, startPosition);
var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
this.insertText(sourceFile, token.getStart(sourceFile), text);
@@ -101557,7 +102364,7 @@ var ts;
}
}
else {
- endNode = node.kind !== 232 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name;
+ endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name;
}
this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " });
};
@@ -101576,6 +102383,9 @@ var ts;
else if (ts.isParameter(before)) {
return {};
}
+ else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) {
+ return { suffix: ", " };
+ }
return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
};
ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) {
@@ -101635,6 +102445,9 @@ var ts;
var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
};
+ ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) {
+ this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
+ };
ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
@@ -101655,32 +102468,34 @@ var ts;
return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
};
ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
- if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) {
- return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
+ switch (node.kind) {
+ case 238 /* ClassDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
+ case 235 /* VariableDeclaration */:
+ case 9 /* StringLiteral */:
+ case 71 /* Identifier */:
+ return { prefix: ", " };
+ case 273 /* PropertyAssignment */:
+ return { suffix: "," + this.newLineCharacter };
+ case 84 /* ExportKeyword */:
+ return { prefix: " " };
+ case 149 /* Parameter */:
+ return {};
+ default:
+ ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it
+ return { suffix: this.newLineCharacter };
}
- else if (ts.isStatement(node) || ts.isClassOrTypeElement(node)) {
- return { suffix: this.newLineCharacter };
- }
- else if (ts.isVariableDeclaration(node) || ts.isStringLiteral(node)) {
- return { prefix: ", " };
- }
- else if (ts.isPropertyAssignment(node)) {
- return { suffix: "," + this.newLineCharacter };
- }
- else if (ts.isParameter(node)) {
- return {};
- }
- return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it
};
ChangeTracker.prototype.insertName = function (sourceFile, node, name) {
ts.Debug.assert(!node.name);
- if (node.kind === 193 /* ArrowFunction */) {
+ if (node.kind === 195 /* ArrowFunction */) {
var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile);
var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile);
if (lparen) {
// `() => {}` --> `function f() {}`
this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " });
- this.deleteNode(sourceFile, arrow);
+ deleteNode(this, sourceFile, arrow);
}
else {
// `x => {}` -> `function f(x) {}`
@@ -101688,14 +102503,14 @@ var ts;
// Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)`
this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */));
}
- if (node.body.kind !== 213 /* Block */) {
+ if (node.body.kind !== 216 /* Block */) {
// `() => 0` => `function f() { return 0; }`
this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " });
this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " });
}
}
else {
- var pos = ts.findChildOfKind(node, node.kind === 192 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end;
+ var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end;
this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
}
};
@@ -101721,7 +102536,7 @@ var ts;
if (index !== containingList.length - 1) {
// any element except the last one
// use next sibling as an anchor
- var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false);
+ var nextToken = ts.getTokenAtPosition(sourceFile, after.end);
if (nextToken && isSeparator(after, nextToken)) {
// for list
// a, b, c
@@ -101826,14 +102641,25 @@ var ts;
}
});
};
- ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () {
+ ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
- this.deletedNodesInLists.forEach(function (node) {
+ var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
+ var _loop_10 = function (sourceFile, node) {
+ if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
+ deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node);
+ }
+ };
+ var this_1 = this;
+ for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
+ var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
+ _loop_10(sourceFile, node);
+ }
+ deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile);
if (node !== ts.last(list))
return;
- var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !_this.deletedNodesInLists.has(n); }, list.length - 2);
+ var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2);
if (lastNonDeletedIndex !== -1) {
_this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
}
@@ -101846,8 +102672,8 @@ var ts;
* so we can only call this once and can't get the non-formatted text separately.
*/
ChangeTracker.prototype.getChanges = function (validate) {
+ this.finishDeleteDeclarations();
this.finishClassesWithNodesInsertedAtStart();
- this.finishTrailingCommaAfterDeletingNodesInList();
var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
@@ -101876,14 +102702,14 @@ var ts;
// order changes by start position
// If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
- var _loop_10 = function (i) {
+ var _loop_11 = function (i) {
ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
});
};
// verify that change intervals do not overlap, except possibly at end points.
for (var i = 0; i < normalized.length - 1; i++) {
- _loop_10(i);
+ _loop_11(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -101944,8 +102770,8 @@ var ts;
})(changesToText || (changesToText = {}));
function applyChanges(text, changes) {
for (var i = changes.length - 1; i >= 0; i--) {
- var change = changes[i];
- text = "" + text.substring(0, change.span.start) + change.newText + text.substring(ts.textSpanEnd(change.span));
+ var _a = changes[i], span = _a.span, newText = _a.newText;
+ text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span));
}
return text;
}
@@ -102147,6 +102973,177 @@ var ts;
return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */
|| ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[`
}
+ var deleteDeclaration;
+ (function (deleteDeclaration_1) {
+ function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) {
+ switch (node.kind) {
+ case 149 /* Parameter */: {
+ var oldFunction = node.parent;
+ if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) {
+ // Lambdas with exactly one parameter are special because, after removal, there
+ // must be an empty parameter list (i.e. `()`) and this won't necessarily be the
+ // case if the parameter is simply removed (e.g. in `x => 1`).
+ var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters,
+ /*parameters*/ undefined, // TODO: GH#18217
+ oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body);
+ // Drop leading and trailing trivia of the new function because we're only going
+ // to replace the span (vs the full span) of the old function - the old leading
+ // and trailing trivia will remain.
+ ts.suppressLeadingAndTrailingTrivia(newFunction);
+ changes.replaceNode(sourceFile, oldFunction, newFunction);
+ }
+ else {
+ deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
+ }
+ break;
+ }
+ case 247 /* ImportDeclaration */:
+ deleteNode(changes, sourceFile, node,
+ // For first import, leave header comment in place
+ node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ break;
+ case 184 /* BindingElement */:
+ var pattern = node.parent;
+ var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements);
+ if (preserveComma) {
+ deleteNode(changes, sourceFile, node);
+ }
+ else {
+ deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
+ }
+ break;
+ case 235 /* VariableDeclaration */:
+ deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node);
+ break;
+ case 148 /* TypeParameter */: {
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(node.parent);
+ if (typeParameters.length === 1) {
+ var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end;
+ var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1);
+ var nextToken = ts.getTokenAtPosition(sourceFile, end);
+ ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */);
+ ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */);
+ changes.deleteNodeRange(sourceFile, previousToken, nextToken);
+ }
+ else {
+ deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
+ }
+ break;
+ }
+ case 251 /* ImportSpecifier */:
+ var namedImports = node.parent;
+ if (namedImports.elements.length === 1) {
+ deleteImportBinding(changes, sourceFile, namedImports);
+ }
+ else {
+ deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
+ }
+ break;
+ case 249 /* NamespaceImport */:
+ deleteImportBinding(changes, sourceFile, node);
+ break;
+ default:
+ if (ts.isImportClause(node.parent) && node.parent.name === node) {
+ deleteDefaultImport(changes, sourceFile, node.parent);
+ }
+ else if (ts.isCallLikeExpression(node.parent)) {
+ deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
+ }
+ else {
+ deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ }
+ }
+ }
+ deleteDeclaration_1.deleteDeclaration = deleteDeclaration;
+ function deleteDefaultImport(changes, sourceFile, importClause) {
+ if (!importClause.namedBindings) {
+ // Delete the whole import
+ deleteNode(changes, sourceFile, importClause.parent);
+ }
+ else {
+ // import |d,| * as ns from './file'
+ var start = importClause.name.getStart(sourceFile);
+ var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end);
+ if (nextToken && nextToken.kind === 26 /* CommaToken */) {
+ // shift first non-whitespace position after comma to the start position of the node
+ var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true);
+ changes.deleteRange(sourceFile, { pos: start, end: end });
+ }
+ else {
+ deleteNode(changes, sourceFile, importClause.name);
+ }
+ }
+ }
+ function deleteImportBinding(changes, sourceFile, node) {
+ if (node.parent.name) {
+ // Delete named imports while preserving the default import
+ // import d|, * as ns| from './file'
+ // import d|, { a }| from './file'
+ var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1));
+ changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end });
+ }
+ else {
+ // Delete the entire import declaration
+ // |import * as ns from './file'|
+ // |import { a } from './file'|
+ var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */);
+ deleteNode(changes, sourceFile, importDecl);
+ }
+ }
+ function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) {
+ var parent = node.parent;
+ if (parent.kind === 272 /* CatchClause */) {
+ // TODO: There's currently no unused diagnostic for this, could be a suggestion
+ changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile));
+ return;
+ }
+ if (parent.declarations.length !== 1) {
+ deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
+ return;
+ }
+ var gp = parent.parent;
+ switch (gp.kind) {
+ case 225 /* ForOfStatement */:
+ case 224 /* ForInStatement */:
+ changes.replaceNode(sourceFile, node, ts.createObjectLiteral());
+ break;
+ case 223 /* ForStatement */:
+ deleteNode(changes, sourceFile, parent);
+ break;
+ case 217 /* VariableStatement */:
+ deleteNode(changes, sourceFile, gp);
+ break;
+ default:
+ ts.Debug.assertNever(gp);
+ }
+ }
+ })(deleteDeclaration || (deleteDeclaration = {}));
+ /** 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);
+ var endPosition = getAdjustedEndPosition(sourceFile, node, options);
+ changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
+ }
+ textChanges_3.deleteNode = deleteNode;
+ function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) {
+ var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile));
+ var index = ts.indexOfNode(containingList, node);
+ ts.Debug.assert(index !== -1);
+ if (containingList.length === 1) {
+ deleteNode(changes, sourceFile, node);
+ return;
+ }
+ // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node.
+ // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`.
+ ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice");
+ deletedNodesInLists.add(node);
+ changes.deleteRange(sourceFile, {
+ pos: startPositionToDeleteNodeInList(sourceFile, node),
+ end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]),
+ });
+ }
})(textChanges = ts.textChanges || (ts.textChanges = {}));
})(ts || (ts = {}));
/* @internal */
@@ -102202,15 +103199,14 @@ var ts;
function createCombinedCodeActions(changes, commands) {
return { changes: changes, commands: commands };
}
+ codefix.createCombinedCodeActions = createCombinedCodeActions;
function createFileTextChanges(fileName, textChanges) {
return { fileName: fileName, textChanges: textChanges };
}
codefix.createFileTextChanges = createFileTextChanges;
function codeFixAll(context, errorCodes, use) {
var commands = [];
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) {
- return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); });
- });
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); });
return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands);
}
codefix.codeFixAll = codeFixAll;
@@ -102223,6 +103219,7 @@ var ts;
}
}
}
+ codefix.eachDiagnostic = eachDiagnostic;
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -102273,7 +103270,7 @@ var ts;
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); },
});
function makeChange(changeTracker, sourceFile, pos) {
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
var decorator = ts.findAncestor(token, ts.isDecorator);
ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator.");
var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined);
@@ -102305,7 +103302,7 @@ var ts;
}); },
});
function getDeclaration(file, pos) {
- var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false);
+ var name = ts.getTokenAtPosition(file, pos);
// For an arrow function with no name, 'name' lands on the first parameter.
return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc);
}
@@ -102352,24 +103349,24 @@ var ts;
}
function isDeclarationWithType(node) {
return ts.isFunctionLikeDeclaration(node) ||
- node.kind === 232 /* VariableDeclaration */ ||
+ node.kind === 235 /* VariableDeclaration */ ||
node.kind === 151 /* PropertySignature */ ||
node.kind === 152 /* PropertyDeclaration */;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 279 /* JSDocAllType */:
- case 280 /* JSDocUnknownType */:
+ case 282 /* JSDocAllType */:
+ case 283 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 283 /* JSDocOptionalType */:
+ case 286 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 282 /* JSDocNonNullableType */:
+ case 285 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 281 /* JSDocNullableType */:
+ case 284 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 285 /* JSDocVariadicType */:
+ case 288 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 284 /* JSDocFunctionType */:
+ case 287 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 162 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -102393,7 +103390,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 285 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -102459,8 +103456,7 @@ var ts;
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); },
});
function doChange(changes, sourceFile, position, checker) {
- var deletedNodes = [];
- var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false));
+ var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position));
if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) {
// Bad input
return undefined;
@@ -102469,20 +103465,20 @@ var ts;
var precedingNode;
var newClassDeclaration;
switch (ctorDeclaration.kind) {
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
precedingNode = ctorDeclaration;
- deleteNode(ctorDeclaration);
+ changes.delete(sourceFile, ctorDeclaration);
newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration);
break;
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
- deleteNode(precedingNode);
+ changes.delete(sourceFile, precedingNode);
}
else {
- deleteNode(ctorDeclaration, /*inList*/ true);
+ changes.delete(sourceFile, ctorDeclaration);
}
break;
}
@@ -102492,22 +103488,6 @@ var ts;
ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
- for (var _i = 0, deletedNodes_1 = deletedNodes; _i < deletedNodes_1.length; _i++) {
- var _a = deletedNodes_1[_i], node = _a.node, inList = _a.inList;
- if (inList) {
- changes.deleteNodeInList(sourceFile, node);
- }
- else {
- changes.deleteNode(sourceFile, node);
- }
- }
- function deleteNode(node, inList) {
- if (inList === void 0) { inList = false; }
- // If parent node has already been deleted, do nothing
- if (!deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n.node); })) {
- deletedNodes.push({ node: node, inList: inList });
- }
- }
function createClassElementsFromSymbol(symbol) {
var memberElements = [];
// all instance members are stored in the "member" array of symbol
@@ -102545,15 +103525,15 @@ var ts;
return;
}
// delete the entire statement if this expression is the sole expression to take care of the semicolon at the end
- var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 216 /* ExpressionStatement */
+ var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */
? assignmentBinaryExpression.parent : assignmentBinaryExpression;
- deleteNode(nodeToDelete);
+ changes.delete(sourceFile, nodeToDelete);
if (!assignmentBinaryExpression.right) {
return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
/*type*/ undefined, /*initializer*/ undefined);
}
switch (assignmentBinaryExpression.right.kind) {
- case 192 /* FunctionExpression */: {
+ case 194 /* FunctionExpression */: {
var functionExpression = assignmentBinaryExpression.right;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
@@ -102561,12 +103541,12 @@ var ts;
ts.copyComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
- case 193 /* ArrowFunction */: {
+ case 195 /* ArrowFunction */: {
var arrowFunction = assignmentBinaryExpression.right;
var arrowFunctionBody = arrowFunction.body;
var bodyBlock = void 0;
// case 1: () => { return [1,2,3] }
- if (arrowFunctionBody.kind === 213 /* Block */) {
+ if (arrowFunctionBody.kind === 216 /* Block */) {
bodyBlock = arrowFunctionBody;
}
// case 2: () => [1,2,3]
@@ -102594,7 +103574,7 @@ var ts;
}
function createClassFromVariableDeclaration(node) {
var initializer = node.initializer;
- if (!initializer || initializer.kind !== 192 /* FunctionExpression */) {
+ if (!initializer || initializer.kind !== 194 /* FunctionExpression */) {
return undefined;
}
if (node.name.kind !== 71 /* Identifier */) {
@@ -102658,10 +103638,10 @@ var ts;
}
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
switch (importNode.kind) {
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference));
break;
- case 187 /* CallExpression */:
+ case 189 /* CallExpression */:
if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default"));
}
@@ -102714,20 +103694,20 @@ var ts;
}
function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) {
switch (statement.kind) {
- case 214 /* VariableStatement */:
+ case 217 /* VariableStatement */:
convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference);
return false;
- case 216 /* ExpressionStatement */: {
+ case 219 /* ExpressionStatement */: {
var expression = statement.expression;
switch (expression.kind) {
- case 187 /* CallExpression */: {
+ case 189 /* CallExpression */: {
if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
// For side-effecting require() call, just make a side-effecting import.
changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference));
}
return false;
}
- case 200 /* BinaryExpression */: {
+ case 202 /* BinaryExpression */: {
var operatorToken = expression.operatorToken;
return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports);
}
@@ -102769,8 +103749,8 @@ var ts;
/** Converts `const name = require("moduleSpecifier").propertyName` */
function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) {
switch (name.kind) {
- case 180 /* ObjectBindingPattern */:
- case 181 /* ArrayBindingPattern */: {
+ case 182 /* ObjectBindingPattern */:
+ case 183 /* ArrayBindingPattern */: {
// `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;`
var tmp = makeUniqueName(propertyName, identifiers);
return [
@@ -102793,7 +103773,7 @@ var ts;
if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) {
if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) {
// `const alias = module.exports;` or `module.exports = alias;` can be removed.
- changes.deleteNode(sourceFile, assignment.parent);
+ changes.delete(sourceFile, assignment.parent);
}
else {
var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
@@ -102824,10 +103804,10 @@ var ts;
case 156 /* GetAccessor */:
case 157 /* SetAccessor */:
// TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`.
- case 271 /* ShorthandPropertyAssignment */:
- case 272 /* SpreadAssignment */:
+ case 274 /* ShorthandPropertyAssignment */:
+ case 275 /* SpreadAssignment */:
return undefined;
- case 270 /* PropertyAssignment */:
+ case 273 /* PropertyAssignment */:
return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer);
case 154 /* MethodDeclaration */:
return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop);
@@ -102884,7 +103864,7 @@ var ts;
changes.insertName(sourceFile, right, name);
var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile);
if (semi)
- changes.deleteNode(sourceFile, semi, { useNonAdjustedEndPosition: true });
+ changes.delete(sourceFile, semi);
}
else {
// `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const `
@@ -102895,7 +103875,7 @@ var ts;
function convertExportsDotXEquals_replaceNode(name, exported) {
var modifiers = [ts.createToken(84 /* ExportKeyword */)];
switch (exported.kind) {
- case 192 /* FunctionExpression */: {
+ case 194 /* FunctionExpression */: {
var expressionName = exported.name;
if (expressionName && expressionName.text !== name) {
// `exports.f = function g() {}` -> `export const f = function g() {}`
@@ -102903,10 +103883,10 @@ var ts;
}
}
// falls through
- case 193 /* ArrowFunction */:
+ case 195 /* ArrowFunction */:
// `exports.f = function() {}` --> `export function f() {}`
return functionExpressionToDeclaration(name, modifiers, exported);
- case 205 /* ClassExpression */:
+ case 207 /* ClassExpression */:
// `exports.C = class {}` --> `export class C {}`
return classExpressionToDeclaration(name, modifiers, exported);
default:
@@ -102924,7 +103904,7 @@ var ts;
*/
function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) {
switch (name.kind) {
- case 180 /* ObjectBindingPattern */: {
+ case 182 /* ObjectBindingPattern */: {
var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) {
return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name)
? undefined
@@ -102935,7 +103915,7 @@ var ts;
}
}
// falls through -- object destructuring has an interesting pattern and must be a variable declaration
- case 181 /* ArrayBindingPattern */: {
+ case 183 /* ArrayBindingPattern */: {
/*
import x from "x";
const [a, b, c] = x;
@@ -103018,11 +103998,11 @@ var ts;
function isFreeIdentifier(node) {
var parent = node.parent;
switch (parent.kind) {
- case 185 /* PropertyAccessExpression */:
+ case 187 /* PropertyAccessExpression */:
return parent.name !== node;
- case 182 /* BindingElement */:
+ case 184 /* BindingElement */:
return parent.propertyName !== node;
- case 248 /* ImportSpecifier */:
+ case 251 /* ImportSpecifier */:
return parent.propertyName !== node;
default:
return true;
@@ -103081,7 +104061,7 @@ var ts;
}); },
});
function getQualifiedName(sourceFile, pos) {
- var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), ts.isQualifiedName);
+ var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName);
ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name.");
return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined;
}
@@ -103126,7 +104106,7 @@ var ts;
},
});
function getClass(sourceFile, pos) {
- return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false)));
+ return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos)));
}
function symbolPointsToNonPrivateMember(symbol) {
return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */);
@@ -103154,7 +104134,7 @@ var ts;
}
}
function getHeritageClauseSymbolTable(classDeclaration, checker) {
- var heritageClauseNode = ts.getClassExtendsHeritageClauseElement(classDeclaration);
+ var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration);
if (!heritageClauseNode)
return ts.createSymbolTable();
var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode);
@@ -103168,42 +104148,109 @@ var ts;
(function (ts) {
var codefix;
(function (codefix) {
- var ChangeTracker = ts.textChanges.ChangeTracker;
+ codefix.importFixId = "fixMissingImport";
+ var errorCodes = [
+ ts.Diagnostics.Cannot_find_name_0.code,
+ ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
+ ts.Diagnostics.Cannot_find_namespace_0.code,
+ ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
+ ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
+ ];
codefix.registerCodeFix({
- errorCodes: [
- ts.Diagnostics.Cannot_find_name_0.code,
- ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code,
- ts.Diagnostics.Cannot_find_namespace_0.code,
- ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code,
- ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code,
- ],
- getCodeActions: function (context) { return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
- ? getActionsForUMDImport(context)
- : getActionsForNonUMDImport(context); },
- // TODO: GH#20315
- fixIds: [],
- getAllCodeActions: ts.notImplemented,
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span;
+ var info = getFixesInfo(context, errorCode, span.start);
+ if (!info)
+ return undefined;
+ var fixes = info.fixes, symbolName = info.symbolName;
+ var quotePreference = ts.getQuotePreference(sourceFile, preferences);
+ return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); });
+ },
+ fixIds: [codefix.importFixId],
+ getAllCodeActions: function (context) {
+ var sourceFile = context.sourceFile, preferences = context.preferences;
+ // Namespace fixes don't conflict, so just build a list.
+ var addToNamespace = [];
+ // Keys are import clause node IDs.
+ var addToExisting = ts.createMap();
+ // Keys are module specifiers.
+ var newImports = ts.createMap();
+ codefix.eachDiagnostic(context, errorCodes, function (diag) {
+ var info = getFixesInfo(context, diag.code, diag.start);
+ if (!info || !info.fixes.length)
+ return;
+ var fixes = info.fixes, symbolName = info.symbolName;
+ var fix = ts.first(fixes);
+ switch (fix.kind) {
+ case 0 /* UseNamespace */:
+ addToNamespace.push(fix);
+ break;
+ case 1 /* AddToExisting */: {
+ var importClause = fix.importClause, importKind = fix.importKind;
+ var key = String(ts.getNodeId(importClause));
+ var entry = addToExisting.get(key);
+ if (!entry) {
+ addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] });
+ }
+ if (importKind === 0 /* Named */) {
+ ts.pushIfUnique(entry.namedImports, symbolName);
+ }
+ else {
+ ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName);
+ entry.defaultImport = symbolName;
+ }
+ break;
+ }
+ case 2 /* AddNew */: {
+ var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind;
+ var entry = newImports.get(moduleSpecifier);
+ if (!entry) {
+ newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined });
+ }
+ switch (importKind) {
+ case 1 /* Default */:
+ ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName);
+ entry.defaultImport = symbolName;
+ break;
+ case 0 /* Named */:
+ ts.pushIfUnique(entry.namedImports, symbolName);
+ break;
+ case 3 /* Equals */:
+ case 2 /* Namespace */:
+ ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName);
+ entry.namespaceLikeImport = { importKind: importKind, name: symbolName };
+ break;
+ }
+ break;
+ }
+ default:
+ ts.Debug.assertNever(fix);
+ }
+ });
+ return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
+ for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) {
+ var fix = addToNamespace_1[_i];
+ addNamespaceQualifier(changes, sourceFile, fix);
+ }
+ addToExisting.forEach(function (_a) {
+ var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports;
+ doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports);
+ });
+ var quotePreference = ts.getQuotePreference(sourceFile, preferences);
+ newImports.forEach(function (imports, moduleSpecifier) {
+ addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports);
+ });
+ }));
+ },
});
- function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) {
- // TODO: GH#20315
- return codefix.createCodeFixActionNoFixId("import", changes, [descriptionDiagnostic].concat(diagnosticArgs));
- }
- function convertToImportCodeFixContext(context, symbolToken, symbolName) {
- var program = context.program;
- var checker = program.getTypeChecker();
- return {
- host: context.host,
- formatContext: context.formatContext,
- sourceFile: context.sourceFile,
- program: program,
- checker: checker,
- compilerOptions: program.getCompilerOptions(),
- getCanonicalFileName: ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(context.host)),
- symbolName: symbolName,
- symbolToken: symbolToken,
- preferences: context.preferences,
- };
- }
+ // Sorted with the preferred fix coming first.
+ var ImportFixKind;
+ (function (ImportFixKind) {
+ ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace";
+ ImportFixKind[ImportFixKind["AddToExisting"] = 1] = "AddToExisting";
+ ImportFixKind[ImportFixKind["AddNew"] = 2] = "AddNew";
+ })(ImportFixKind || (ImportFixKind = {}));
var ImportKind;
(function (ImportKind) {
ImportKind[ImportKind["Named"] = 0] = "Named";
@@ -103211,13 +104258,13 @@ var ts;
ImportKind[ImportKind["Namespace"] = 2] = "Namespace";
ImportKind[ImportKind["Equals"] = 3] = "Equals";
})(ImportKind || (ImportKind = {}));
- function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken, preferences) {
+ function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, allSourceFiles, formatContext, symbolToken, preferences) {
var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles);
ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }));
// We sort the best codefixes first, so taking `first` is best for completions.
var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier;
- var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken, preferences: preferences };
- return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) };
+ var fix = ts.first(getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences));
+ return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) };
}
codefix.getImportCompletionAction = getImportCompletionAction;
function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) {
@@ -103237,23 +104284,16 @@ var ts;
});
return result;
}
- function getCodeActionsForImport(exportInfos, context) {
- var result = [];
- getCodeActionsForImport_separateExistingAndNew(exportInfos, context, result, result);
- return result;
+ function getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences) {
+ var checker = program.getTypeChecker();
+ var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); });
+ var useNamespace = tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker);
+ var addToExisting = tryAddToExistingImport(existingImports);
+ // Don't bother providing an action to add a new import if we can add to an existing one.
+ var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences);
+ return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport);
}
- function getCodeActionsForImport_separateExistingAndNew(exportInfos, context, useExisting, addNew) {
- var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, context.checker, context.sourceFile); });
- ts.append(useExisting, tryUseExistingNamespaceImport(existingImports, context, context.symbolToken, context.checker));
- var addToExisting = tryAddToExistingImport(existingImports, context);
- if (addToExisting) {
- useExisting.push(addToExisting);
- }
- else { // Don't bother providing an action to add a new import if we can add to an existing one.
- getCodeActionsForAddImport(exportInfos, context, existingImports, addNew);
- }
- }
- function tryUseExistingNamespaceImport(existingImports, context, symbolToken, checker) {
+ function tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker) {
// It is possible that multiple import statements with the same specifier exist in the file.
// e.g.
//
@@ -103270,29 +104310,31 @@ var ts;
var declaration = _a.declaration;
var namespace = getNamespaceImportName(declaration);
if (namespace) {
- var moduleSymbol = namespace && checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace));
- if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) {
- return getCodeActionForUseExistingNamespaceImport(namespace.text, context, symbolToken);
+ var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace));
+ if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) {
+ return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, symbolToken: symbolToken };
}
}
});
}
- function tryAddToExistingImport(existingImports, context) {
+ function tryAddToExistingImport(existingImports) {
return ts.firstDefined(existingImports, function (_a) {
var declaration = _a.declaration, importKind = _a.importKind;
- if (declaration.kind === 244 /* ImportDeclaration */ && declaration.importClause) {
- var changes = tryUpdateExistingImport(context, declaration.importClause, importKind);
- if (changes) {
- var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText());
- return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [context.symbolName, moduleSpecifierWithoutQuotes], changes);
- }
- }
+ if (declaration.kind !== 247 /* ImportDeclaration */)
+ return undefined;
+ var importClause = declaration.importClause;
+ if (!importClause)
+ return undefined;
+ var name = importClause.name, namedBindings = importClause.namedBindings;
+ return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */)
+ ? { kind: 1 /* AddToExisting */, importClause: importClause, importKind: importKind }
+ : undefined;
});
}
function getNamespaceImportName(declaration) {
- if (declaration.kind === 244 /* ImportDeclaration */) {
+ if (declaration.kind === 247 /* ImportDeclaration */) {
var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings;
- return namedBindings && namedBindings.kind === 246 /* NamespaceImport */ ? namedBindings.name : undefined;
+ return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined;
}
else {
return declaration.name;
@@ -103303,141 +104345,61 @@ var ts;
var imports = _b.imports;
return ts.mapDefined(imports, function (moduleSpecifier) {
var i = ts.importFromModuleSpecifier(moduleSpecifier);
- return (i.kind === 244 /* ImportDeclaration */ || i.kind === 243 /* ImportEqualsDeclaration */)
+ return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */)
&& checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined;
});
}
- function getCodeActionForNewImport(context, _a) {
- var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind;
- var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences;
- var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier);
- var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifierWithoutQuotes, ts.getQuotePreference(sourceFile, preferences));
- var importDecl = importKind !== 3 /* Equals */
- ? ts.createImportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, createImportClauseOfKind(importKind, symbolName), quotedModuleSpecifier)
- : ts.createImportEqualsDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier));
- var changes = ChangeTracker.with(context, function (t) { return ts.insertImport(t, sourceFile, importDecl); });
- // if this file doesn't have any import statements, insert an import statement and then insert a new line
- // between the only import statement and user code. Otherwise just insert the statement because chances
- // are there are already a new line separating code and import statements.
- return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes);
- }
- function createImportClauseOfKind(kind, symbolName) {
- var id = ts.createIdentifier(symbolName);
- switch (kind) {
- case 1 /* Default */:
- return ts.createImportClause(id, /*namedBindings*/ undefined);
- case 2 /* Namespace */:
- return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(id));
- case 0 /* Named */:
- return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, id)]));
- default:
- ts.Debug.assertNever(kind);
- }
- }
function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) {
var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind;
var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences);
- return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); });
+ return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ kind: 2 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }); }); });
});
// Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together
return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; }));
}
- function getCodeActionsForAddImport(exportInfos, ctx, existingImports, addNew) {
+ function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences) {
var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier);
- var newImportInfos = existingDeclaration
- ? [existingDeclaration]
- : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.host, ctx.preferences);
- for (var _i = 0, newImportInfos_1 = newImportInfos; _i < newImportInfos_1.length; _i++) {
- var info = newImportInfos_1[_i];
- addNew.push(getCodeActionForNewImport(ctx, info));
- }
+ return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, exportInfos, host, preferences);
}
function newImportInfoFromExistingSpecifier(_a) {
var declaration = _a.declaration, importKind = _a.importKind;
- var expression = declaration.kind === 244 /* ImportDeclaration */
+ var expression = declaration.kind === 247 /* ImportDeclaration */
? declaration.moduleSpecifier
- : declaration.moduleReference.kind === 254 /* ExternalModuleReference */
+ : declaration.moduleReference.kind === 257 /* ExternalModuleReference */
? declaration.moduleReference.expression
: undefined;
- return expression && ts.isStringLiteral(expression) ? { moduleSpecifier: expression.text, importKind: importKind } : undefined;
+ return expression && ts.isStringLiteral(expression) ? { kind: 2 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined;
}
- function tryUpdateExistingImport(context, importClause, importKind) {
- var symbolName = context.symbolName, sourceFile = context.sourceFile;
- var name = importClause.name;
- var namedBindings = (importClause.kind !== 243 /* ImportEqualsDeclaration */ && importClause).namedBindings; // TODO: GH#18217
- switch (importKind) {
- case 1 /* Default */:
- return name ? undefined : ChangeTracker.with(context, function (t) {
- return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings));
- });
- case 0 /* Named */: {
- var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName));
- if (namedBindings && namedBindings.kind === 247 /* NamedImports */ && namedBindings.elements.length !== 0) {
- // There are already named imports; add another.
- return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); });
- }
- if (!namedBindings || namedBindings.kind === 247 /* NamedImports */ && namedBindings.elements.length === 0) {
- return ChangeTracker.with(context, function (t) {
- return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1])));
- });
- }
- return undefined;
- }
- case 2 /* Namespace */:
- return namedBindings ? undefined : ChangeTracker.with(context, function (t) {
- return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName))));
- });
- case 3 /* Equals */:
- return undefined;
- default:
- ts.Debug.assertNever(importKind);
- }
+ function getFixesInfo(context, errorCode, pos) {
+ var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos);
+ var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
+ ? getFixesInfoForUMDImport(context, symbolToken)
+ : getFixesInfoForNonUMDImport(context, symbolToken);
+ return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) });
}
- function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) {
- var symbolName = context.symbolName, sourceFile = context.sourceFile;
- /**
- * Cases:
- * import * as ns from "mod"
- * import default, * as ns from "mod"
- * import ns = require("mod")
- *
- * Because there is no import list, we alter the reference to include the
- * namespace instead of altering the import declaration. For example, "foo" would
- * become "ns.foo"
- */
- var changes = ChangeTracker.with(context, function (tracker) {
- return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken));
- });
- return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes);
+ function getFixesInfoForUMDImport(_a, token) {
+ var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences;
+ var checker = program.getTypeChecker();
+ var umdSymbol = getUmdSymbol(token, checker);
+ if (!umdSymbol)
+ return undefined;
+ var symbol = checker.getAliasedSymbol(umdSymbol);
+ var symbolName = umdSymbol.name;
+ var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()) }];
+ var fixes = getFixForImport(exportInfos, symbolName, token, program, sourceFile, host, preferences);
+ return { fixes: fixes, symbolName: symbolName };
}
- function getActionsForUMDImport(context) {
- var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false);
- var checker = context.program.getTypeChecker();
- var umdSymbol;
- if (ts.isIdentifier(token)) {
- // try the identifier to see if it is the umd symbol
- umdSymbol = checker.getSymbolAtLocation(token);
- }
- if (!ts.isUMDExportSymbol(umdSymbol)) {
- // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
- var parent = token.parent;
- var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent);
- if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 260 /* JsxOpeningFragment */) {
- umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false);
- }
- }
- if (ts.isUMDExportSymbol(umdSymbol)) {
- var symbol = checker.getAliasedSymbol(umdSymbol);
- if (symbol) {
- return getCodeActionsForImport([{ moduleSymbol: symbol, importKind: getUmdImportKind(context.program.getCompilerOptions()) }], convertToImportCodeFixContext(context, token, umdSymbol.name));
- }
- }
- return undefined;
+ function getUmdSymbol(token, checker) {
+ // try the identifier to see if it is the umd symbol
+ var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined;
+ if (ts.isUMDExportSymbol(umdSymbol))
+ return umdSymbol;
+ // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
+ var parent = token.parent;
+ return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent)
+ ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol)
+ : undefined;
}
function getUmdImportKind(compilerOptions) {
// Import a synthetic `default` if enabled.
@@ -103461,11 +104423,10 @@ var ts;
return ts.Debug.assertNever(moduleKind);
}
}
- function getActionsForNonUMDImport(context) {
+ function getFixesInfoForNonUMDImport(_a, symbolToken) {
+ var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences;
// This will always be an Identifier, since the diagnostics we fix only fail on identifiers.
- var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken;
var checker = program.getTypeChecker();
- var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false);
// If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead.
var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent)
&& symbolToken.parent.tagName === symbolToken
@@ -103475,14 +104436,14 @@ var ts;
if (!symbolName)
return undefined;
// "default" is a keyword and not a legal identifier for the import, so we don't expect it here
- ts.Debug.assert(symbolName !== "default");
- var addToExistingDeclaration = [];
- var addNewDeclaration = [];
- getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).forEach(function (exportInfos) {
- getCodeActionsForImport_separateExistingAndNew(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName), addToExistingDeclaration, addNewDeclaration);
- });
- return addToExistingDeclaration.concat(addNewDeclaration);
+ ts.Debug.assert(symbolName !== "default" /* Default */);
+ var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) {
+ var _ = _a[0], exportInfos = _a[1];
+ return getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences);
+ }));
+ return { fixes: fixes, symbolName: symbolName };
}
+ // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported.
function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) {
// For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once.
// Maps symbol id to info for modules providing that symbol (original export + re-exports).
@@ -103495,35 +104456,121 @@ var ts;
// check the default export
var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol);
if (defaultExport) {
- var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
- if ((localSymbol && localSymbol.escapedName === symbolName ||
- getEscapedNameForExportDefault(defaultExport) === symbolName ||
- moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) {
- addSymbol(moduleSymbol, localSymbol || defaultExport, 1 /* Default */);
+ var info = getDefaultExportInfo(defaultExport, moduleSymbol, program);
+ if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) {
+ addSymbol(moduleSymbol, defaultExport, 1 /* Default */);
}
}
// check exports with the same name
var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol);
- if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
+ if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) {
addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */);
}
- function getEscapedNameForExportDefault(symbol) {
- return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) {
- if (ts.isExportAssignment(declaration)) {
- if (ts.isIdentifier(declaration.expression)) {
- return declaration.expression.escapedText;
- }
- }
- else if (ts.isExportSpecifier(declaration)) {
- ts.Debug.assert(declaration.name.escapedText === "default" /* Default */);
- return declaration.propertyName && declaration.propertyName.escapedText;
- }
- });
- }
});
return originalSymbolToExportInfos;
}
- function checkSymbolHasMeaning(_a, meaning) {
+ function getDefaultExportInfo(defaultExport, moduleSymbol, program) {
+ var checker = program.getTypeChecker();
+ var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport);
+ if (localSymbol)
+ return { symbolForMeaning: localSymbol, name: localSymbol.name };
+ var name = getNameForExportDefault(defaultExport);
+ if (name !== undefined)
+ return { symbolForMeaning: defaultExport, name: name };
+ if (defaultExport.flags & 2097152 /* Alias */) {
+ var aliased = checker.getAliasedSymbol(defaultExport);
+ return getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program);
+ }
+ else {
+ var moduleName = moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target);
+ return moduleName === undefined ? undefined : { symbolForMeaning: defaultExport, name: moduleName };
+ }
+ }
+ function getNameForExportDefault(symbol) {
+ return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) {
+ if (ts.isExportAssignment(declaration)) {
+ if (ts.isIdentifier(declaration.expression)) {
+ return declaration.expression.text;
+ }
+ }
+ else if (ts.isExportSpecifier(declaration)) {
+ ts.Debug.assert(declaration.name.text === "default" /* Default */);
+ return declaration.propertyName && declaration.propertyName.text;
+ }
+ });
+ }
+ function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) {
+ var diag;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) {
+ diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference);
+ });
+ return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports);
+ }
+ function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) {
+ switch (fix.kind) {
+ case 0 /* UseNamespace */:
+ addNamespaceQualifier(changes, sourceFile, fix);
+ return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName];
+ case 1 /* AddToExisting */: {
+ var importClause = fix.importClause, importKind = fix.importKind;
+ doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray);
+ var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText());
+ return [ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes];
+ }
+ case 2 /* AddNew */: {
+ var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier;
+ addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined }
+ : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined }
+ : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } });
+ return [ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier];
+ }
+ default:
+ return ts.Debug.assertNever(fix);
+ }
+ }
+ function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) {
+ if (defaultImport) {
+ ts.Debug.assert(!clause.name);
+ changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " });
+ }
+ if (namedImports.length) {
+ var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); });
+ if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) {
+ for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) {
+ var spec = specifiers_1[_i];
+ changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec);
+ }
+ }
+ else {
+ if (specifiers.length) {
+ var namedImports_1 = ts.createNamedImports(specifiers);
+ if (clause.namedBindings) {
+ changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1);
+ }
+ else {
+ changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1);
+ }
+ }
+ }
+ }
+ }
+ function addNamespaceQualifier(changes, sourceFile, _a) {
+ var namespacePrefix = _a.namespacePrefix, symbolToken = _a.symbolToken;
+ changes.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken));
+ }
+ function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) {
+ var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport;
+ var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference);
+ if (defaultImport !== undefined || namedImports.length) {
+ ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference));
+ }
+ if (namespaceLikeImport) {
+ ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */
+ ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier))
+ : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier));
+ }
+ }
+ function symbolHasMeaning(_a, meaning) {
var declarations = _a.declarations;
return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); });
}
@@ -103624,7 +104671,7 @@ var ts;
// This is the identifier of the misspelled word. eg:
// this.speling = 1;
// ^^^^^^^
- var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852
+ var node = ts.getTokenAtPosition(sourceFile, pos);
var checker = context.program.getTypeChecker();
var suggestion;
if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) {
@@ -103696,46 +104743,99 @@ var ts;
var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker());
if (!info)
return undefined;
- var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
- var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, context.preferences);
+ if (info.kind === InfoKind.enum) {
+ var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); });
+ return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)];
+ }
+ var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
+ var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences);
var addMember = inJs ?
- ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) :
- getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic);
+ ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic)) :
+ getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, parentDeclaration, token, makeStatic);
return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember);
},
fixIds: [fixId],
getAllCodeActions: function (context) {
- var seenNames = ts.createMap();
- return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- var program = context.program, preferences = context.preferences;
- var info = getInfo(diag.file, diag.start, program.getTypeChecker());
- if (!info)
- return;
- var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
- if (!ts.addToSeen(seenNames, token.text)) {
- return;
- }
- // Always prefer to add a method declaration if possible.
- if (call) {
- addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs, preferences);
- }
- else {
- if (inJs) {
- addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic);
+ var program = context.program, preferences = context.preferences;
+ var checker = program.getTypeChecker();
+ var seen = ts.createMap();
+ var classToMembers = new ts.NodeMap();
+ return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) {
+ codefix.eachDiagnostic(context, errorCodes, function (diag) {
+ var info = getInfo(diag.file, diag.start, checker);
+ if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) {
+ return;
+ }
+ if (info.kind === InfoKind.enum) {
+ var token = info.token, parentDeclaration = info.parentDeclaration;
+ addEnumMemberDeclaration(changes, checker, token, parentDeclaration);
}
else {
- var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token);
- addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic);
+ var parentDeclaration = info.parentDeclaration, token_2 = info.token;
+ var infos = classToMembers.getOrUpdate(parentDeclaration, function () { return []; });
+ if (!infos.some(function (i) { return i.token.text === token_2.text; }))
+ infos.push(info);
}
- }
- });
+ });
+ classToMembers.forEach(function (infos, classDeclaration) {
+ var superClasses = getAllSuperClasses(classDeclaration, checker);
+ var _loop_12 = function (info) {
+ // If some superclass added this property, don't add it again.
+ if (superClasses.some(function (superClass) {
+ var superInfos = classToMembers.get(superClass);
+ return !!superInfos && superInfos.some(function (_a) {
+ var token = _a.token;
+ return token.text === info.token.text;
+ });
+ }))
+ return "continue";
+ var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call;
+ // Always prefer to add a method declaration if possible.
+ if (call) {
+ addMethodDeclaration(context, changes, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences);
+ }
+ else {
+ if (inJs) {
+ addMissingMemberInJs(changes, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic);
+ }
+ else {
+ var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token);
+ addPropertyDeclaration(changes, classDeclarationSourceFile, parentDeclaration, token.text, typeNode, makeStatic);
+ }
+ }
+ };
+ for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
+ var info = infos_1[_i];
+ _loop_12(info);
+ }
+ });
+ }));
},
});
+ function getAllSuperClasses(cls, checker) {
+ var res = [];
+ while (cls) {
+ var superElement = ts.getClassExtendsHeritageElement(cls);
+ var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression);
+ var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike);
+ if (superDecl) {
+ res.push(superDecl);
+ }
+ cls = superDecl;
+ }
+ return res;
+ }
+ var InfoKind;
+ (function (InfoKind) {
+ InfoKind[InfoKind["enum"] = 0] = "enum";
+ InfoKind[InfoKind["class"] = 1] = "class";
+ })(InfoKind || (InfoKind = {}));
function getInfo(tokenSourceFile, tokenPos, checker) {
// The identifier of the missing property. eg:
// this.missing = 1;
// ^^^^^^^
- var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos);
if (!ts.isIdentifier(token)) {
return undefined;
}
@@ -103744,14 +104844,21 @@ var ts;
return undefined;
var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression));
var symbol = leftExpressionType.symbol;
- var classDeclaration = symbol && symbol.declarations && ts.find(symbol.declarations, ts.isClassLike);
- if (!classDeclaration)
+ if (!symbol || !symbol.declarations)
return undefined;
- var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol);
- var classDeclarationSourceFile = classDeclaration.getSourceFile();
- var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile);
- var call = ts.tryCast(parent.parent, ts.isCallExpression);
- return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call };
+ var classDeclaration = ts.find(symbol.declarations, ts.isClassLike);
+ if (classDeclaration) {
+ var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol);
+ var classDeclarationSourceFile = classDeclaration.getSourceFile();
+ var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile);
+ var call = ts.tryCast(parent.parent, ts.isCallExpression);
+ return { kind: InfoKind.class, token: token, parentDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call };
+ }
+ var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration);
+ if (enumDeclaration) {
+ return { kind: InfoKind.enum, token: token, parentDeclaration: enumDeclaration };
+ }
+ return undefined;
}
function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) {
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); });
@@ -103760,7 +104867,7 @@ var ts;
}
function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) {
if (makeStatic) {
- if (classDeclaration.kind === 205 /* ClassExpression */) {
+ if (classDeclaration.kind === 207 /* ClassExpression */) {
return;
}
var className = classDeclaration.name.getText();
@@ -103786,7 +104893,7 @@ var ts;
}
function getTypeNode(checker, classDeclaration, token) {
var typeNode;
- if (token.parent.parent.kind === 200 /* BinaryExpression */) {
+ if (token.parent.parent.kind === 202 /* BinaryExpression */) {
var binaryExpression = token.parent.parent;
var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left;
var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); // TODO: GH#18217
@@ -103840,11 +104947,11 @@ var ts;
return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]);
}
function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) {
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); });
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); });
return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members);
}
- function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) {
- var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic, preferences);
+ function addMethodDeclaration(context, changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) {
+ var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences);
var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */);
if (containingMethodDeclaration && containingMethodDeclaration.parent === classDeclaration) {
changeTracker.insertNodeAfter(classDeclarationSourceFile, containingMethodDeclaration, methodDeclaration);
@@ -103853,6 +104960,19 @@ var ts;
changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration);
}
}
+ function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) {
+ /**
+ * create initializer only literal enum that has string initializer.
+ * value of initializer is a string literal that equal to name of enum member.
+ * numeric enum or empty enum will not create initializer.
+ */
+ var hasStringInitializer = ts.some(enumDeclaration.members, function (member) {
+ var type = checker.getTypeAtLocation(member);
+ return !!(type && type.flags & 68 /* StringLike */);
+ });
+ var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined);
+ changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember))));
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -103886,7 +105006,7 @@ var ts;
return { type: "install package", file: fileName, packageName: packageName };
}
function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) {
- var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text;
+ var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text;
var packageName = ts.getPackageName(moduleName).packageName;
return diagCode === errorCodeCannotFindModule
? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined)
@@ -103927,11 +105047,11 @@ var ts;
function getClass(sourceFile, pos) {
// Token is the identifier in the case of a class declaration
// or the class keyword token in the case of a class expression.
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
return ts.cast(token.parent, ts.isClassLike);
}
function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) {
- var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration);
+ var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration);
var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
// Note that this is ultimately derived from a map indexed by symbol names,
// so duplicates cannot occur.
@@ -103981,10 +105101,10 @@ var ts;
});
function doChange(changes, sourceFile, constructor, superCall) {
changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall);
- changes.deleteNode(sourceFile, superCall);
+ changes.delete(sourceFile, superCall);
}
function getNodes(sourceFile, pos) {
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
if (token.kind !== 99 /* ThisKeyword */)
return undefined;
var constructor = ts.getContainingFunction(token);
@@ -104023,7 +105143,7 @@ var ts;
}); },
});
function getNode(sourceFile, pos) {
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */);
return token.parent;
}
@@ -104059,7 +105179,7 @@ var ts;
}); },
});
function getNodes(sourceFile, pos) {
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
var heritageClauses = ts.getContainingClass(token).heritageClauses;
var extendsToken = heritageClauses[0].getFirstToken();
return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined;
@@ -104115,7 +105235,7 @@ var ts;
}); },
});
function getInfo(sourceFile, pos, diagCode) {
- var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var node = ts.getTokenAtPosition(sourceFile, pos);
if (!ts.isIdentifier(node))
return undefined;
return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined };
@@ -104149,25 +105269,30 @@ var ts;
getCodeActions: function (context) {
var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program;
var checker = program.getTypeChecker();
- var startToken = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
- var importDecl = tryGetFullImport(startToken);
+ var sourceFiles = program.getSourceFiles();
+ var token = ts.getTokenAtPosition(sourceFile, context.span.start);
+ var importDecl = tryGetFullImport(token);
if (importDecl) {
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); });
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); });
return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
}
- var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, startToken, /*deleted*/ undefined, checker, /*isFixAll*/ false); });
+ var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) {
+ return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false);
+ });
if (delDestructure.length) {
return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
}
- var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(t, sourceFile, startToken, /*deleted*/ undefined); });
+ var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); });
if (delVar.length) {
return [codefix.createCodeFixAction(fixName, delVar, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
}
- var token = getToken(sourceFile, ts.textSpanEnd(context.span));
var result = [];
- var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined, checker, /*isFixAll*/ false); });
+ var deletion = ts.textChanges.ChangeTracker.with(context, function (t) {
+ return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false);
+ });
if (deletion.length) {
- result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, token.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations));
+ var name = ts.isComputedPropertyName(token.parent) ? token.parent : token;
+ result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations));
}
var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); });
if (prefix.length) {
@@ -104177,32 +105302,28 @@ var ts;
},
fixIds: [fixIdPrefix, fixIdDelete],
getAllCodeActions: function (context) {
- // Track a set of deleted nodes that may be ancestors of other marked for deletion -- only delete the ancestors.
- var deleted = new ts.NodeSet();
var sourceFile = context.sourceFile, program = context.program;
var checker = program.getTypeChecker();
+ var sourceFiles = program.getSourceFiles();
return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- var startToken = ts.getTokenAtPosition(sourceFile, diag.start, /*includeJsDocComment*/ false);
- var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file);
+ var token = ts.getTokenAtPosition(sourceFile, diag.start);
switch (context.fixId) {
case fixIdPrefix:
if (ts.isIdentifier(token) && canPrefix(token)) {
tryPrefixDeclaration(changes, diag.code, sourceFile, token);
}
break;
- case fixIdDelete:
- // Ignore if this range was already deleted.
- if (deleted.some(function (d) { return ts.rangeContainsPosition(d, diag.start); }))
- break;
- var importDecl = tryGetFullImport(startToken);
+ case fixIdDelete: {
+ var importDecl = tryGetFullImport(token);
if (importDecl) {
- changes.deleteNode(sourceFile, importDecl);
+ changes.delete(sourceFile, importDecl);
}
- else if (!tryDeleteFullDestructure(changes, sourceFile, startToken, deleted, checker, /*isFixAll*/ true) &&
- !tryDeleteFullVariableStatement(changes, sourceFile, startToken, deleted)) {
- tryDeleteDeclaration(changes, sourceFile, token, deleted, checker, /*isFixAll*/ true);
+ else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) &&
+ !tryDeleteFullVariableStatement(sourceFile, token, changes)) {
+ tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true);
}
break;
+ }
default:
ts.Debug.fail(JSON.stringify(context.fixId));
}
@@ -104210,49 +105331,29 @@ var ts;
},
});
// Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
- function tryGetFullImport(startToken) {
- return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined;
+ function tryGetFullImport(token) {
+ return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined;
}
- function tryDeleteFullDestructure(changes, sourceFile, startToken, deletedAncestors, checker, isFixAll) {
- if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent))
+ function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
+ if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent))
return false;
- var decl = ts.cast(startToken.parent, ts.isObjectBindingPattern).parent;
- switch (decl.kind) {
- case 232 /* VariableDeclaration */:
- tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors);
- break;
- case 149 /* Parameter */:
- if (!mayDeleteParameter(decl, checker, isFixAll))
- break;
- if (deletedAncestors)
- deletedAncestors.add(decl);
- changes.deleteNodeInList(sourceFile, decl);
- break;
- case 182 /* BindingElement */:
- if (deletedAncestors)
- deletedAncestors.add(decl);
- changes.deleteNode(sourceFile, decl);
- break;
- default:
- return ts.Debug.assertNever(decl);
+ var decl = token.parent.parent;
+ if (decl.kind === 149 /* Parameter */) {
+ tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll);
+ }
+ else {
+ changes.delete(sourceFile, decl);
}
return true;
}
- function tryDeleteFullVariableStatement(changes, sourceFile, startToken, deletedAncestors) {
- var declarationList = ts.tryCast(startToken.parent, ts.isVariableDeclarationList);
- if (declarationList && declarationList.getChildren(sourceFile)[0] === startToken) {
- if (deletedAncestors)
- deletedAncestors.add(declarationList);
- changes.deleteNode(sourceFile, declarationList.parent.kind === 214 /* VariableStatement */ ? declarationList.parent : declarationList);
+ function tryDeleteFullVariableStatement(sourceFile, token, changes) {
+ var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList);
+ if (declarationList && declarationList.getChildren(sourceFile)[0] === token) {
+ changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList);
return true;
}
return false;
}
- function getToken(sourceFile, pos) {
- var token = ts.findPrecedingToken(pos, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true);
- // this handles var ["computed"] = 12;
- return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token;
- }
function tryPrefixDeclaration(changes, errorCode, sourceFile, token) {
// Don't offer to prefix a property.
if (errorCode !== ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code && ts.isIdentifier(token) && canPrefix(token)) {
@@ -104263,209 +105364,61 @@ var ts;
switch (token.parent.kind) {
case 149 /* Parameter */:
return true;
- case 232 /* VariableDeclaration */: {
+ case 235 /* VariableDeclaration */: {
var varDecl = token.parent;
switch (varDecl.parent.parent.kind) {
- case 222 /* ForOfStatement */:
- case 221 /* ForInStatement */:
+ case 225 /* ForOfStatement */:
+ case 224 /* ForInStatement */:
return true;
}
}
}
return false;
}
- function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors, checker, isFixAll) {
- tryDeleteDeclarationWorker(changes, sourceFile, token, deletedAncestors, checker, isFixAll);
+ function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) {
+ tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll);
if (ts.isIdentifier(token))
deleteAssignments(changes, sourceFile, token, checker);
}
function deleteAssignments(changes, sourceFile, token, checker) {
ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) {
- if (ref.parent.kind === 185 /* PropertyAccessExpression */)
+ if (ref.parent.kind === 187 /* PropertyAccessExpression */)
ref = ref.parent;
- if (ref.parent.kind === 200 /* BinaryExpression */ && ref.parent.parent.kind === 216 /* ExpressionStatement */) {
- changes.deleteNode(sourceFile, ref.parent.parent);
+ if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) {
+ changes.delete(sourceFile, ref.parent.parent);
}
});
}
- function tryDeleteDeclarationWorker(changes, sourceFile, token, deletedAncestors, checker, isFixAll) {
+ function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) {
var parent = token.parent;
- switch (parent.kind) {
- case 232 /* VariableDeclaration */:
- tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors);
- break;
- case 148 /* TypeParameter */:
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent);
- if (typeParameters.length === 1) {
- var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end;
- var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1, /*includeJsDocComment*/ false);
- var nextToken = ts.getTokenAtPosition(sourceFile, end, /*includeJsDocComment*/ false);
- ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */);
- ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */);
- changes.deleteNodeRange(sourceFile, previousToken, nextToken);
- }
- else {
- changes.deleteNodeInList(sourceFile, parent);
- }
- break;
- case 149 /* Parameter */:
- if (!mayDeleteParameter(parent, checker, isFixAll))
- break;
- var oldFunction = parent.parent;
- if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) {
- // Lambdas with exactly one parameter are special because, after removal, there
- // must be an empty parameter list (i.e. `()`) and this won't necessarily be the
- // case if the parameter is simply removed (e.g. in `x => 1`).
- var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters,
- /*parameters*/ undefined, // TODO: GH#18217
- oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body);
- // Drop leading and trailing trivia of the new function because we're only going
- // to replace the span (vs the full span) of the old function - the old leading
- // and trailing trivia will remain.
- ts.suppressLeadingAndTrailingTrivia(newFunction);
- changes.replaceNode(sourceFile, oldFunction, newFunction);
- }
- else {
- changes.deleteNodeInList(sourceFile, parent);
- }
- break;
- case 182 /* BindingElement */: {
- var pattern = parent.parent;
- var preserveComma = pattern.kind === 181 /* ArrayBindingPattern */ && parent !== ts.last(pattern.elements);
- if (preserveComma) {
- changes.deleteNode(sourceFile, parent);
- }
- else {
- changes.deleteNodeInList(sourceFile, parent);
- }
- break;
- }
- // handle case where 'import a = A;'
- case 243 /* ImportEqualsDeclaration */:
- var importEquals = ts.getAncestor(token, 243 /* ImportEqualsDeclaration */);
- changes.deleteNode(sourceFile, importEquals);
- break;
- case 248 /* ImportSpecifier */:
- var namedImports = parent.parent;
- if (namedImports.elements.length === 1) {
- tryDeleteNamedImportBinding(changes, sourceFile, namedImports);
- }
- else {
- // delete import specifier
- changes.deleteNodeInList(sourceFile, parent);
- }
- break;
- case 245 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *'
- var importClause = parent;
- if (!importClause.namedBindings) { // |import d from './file'|
- changes.deleteNode(sourceFile, ts.getAncestor(importClause, 244 /* ImportDeclaration */));
- }
- else {
- // import |d,| * as ns from './file'
- var start = importClause.name.getStart(sourceFile);
- var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false);
- if (nextToken && nextToken.kind === 26 /* CommaToken */) {
- // shift first non-whitespace position after comma to the start position of the node
- var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true);
- changes.deleteRange(sourceFile, { pos: start, end: end });
- }
- else {
- changes.deleteNode(sourceFile, importClause.name);
- }
- }
- break;
- case 246 /* NamespaceImport */:
- tryDeleteNamedImportBinding(changes, sourceFile, parent);
- break;
- default:
- if (ts.isDeclarationName(token)) {
- if (deletedAncestors)
- deletedAncestors.add(token.parent);
- changes.deleteNode(sourceFile, token.parent);
- }
- else if (ts.isLiteralComputedPropertyDeclarationName(token)) {
- if (deletedAncestors)
- deletedAncestors.add(token.parent.parent);
- changes.deleteNode(sourceFile, token.parent.parent);
- }
- break;
- }
- }
- function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) {
- if (namedBindings.parent.name) {
- // Delete named imports while preserving the default import
- // import d|, * as ns| from './file'
- // import d|, { a }| from './file'
- var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false);
- if (previousToken && previousToken.kind === 26 /* CommaToken */) {
- changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end });
- }
+ if (ts.isParameter(parent)) {
+ tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll);
}
else {
- // Delete the entire import declaration
- // |import * as ns from './file'|
- // |import { a } from './file'|
- var importDecl = ts.getAncestor(namedBindings, 244 /* ImportDeclaration */);
- changes.deleteNode(sourceFile, importDecl);
+ changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent);
}
}
- // token.parent is a variableDeclaration
- function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) {
- switch (varDecl.parent.parent.kind) {
- case 220 /* ForStatement */: {
- var forStatement = varDecl.parent.parent;
- var forInitializer = forStatement.initializer;
- if (forInitializer.declarations.length === 1) {
- if (deletedAncestors)
- deletedAncestors.add(forInitializer);
- changes.deleteNode(sourceFile, forInitializer);
- }
- else {
- if (deletedAncestors)
- deletedAncestors.add(varDecl);
- changes.deleteNodeInList(sourceFile, varDecl);
- }
- break;
- }
- case 222 /* ForOfStatement */:
- var forOfStatement = varDecl.parent.parent;
- ts.Debug.assert(forOfStatement.initializer.kind === 233 /* VariableDeclarationList */);
- var forOfInitializer = forOfStatement.initializer;
- if (deletedAncestors)
- deletedAncestors.add(forOfInitializer.declarations[0]);
- changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral());
- break;
- case 221 /* ForInStatement */:
- case 230 /* TryStatement */:
- break;
- default:
- var variableStatement = varDecl.parent.parent;
- if (variableStatement.declarationList.declarations.length === 1) {
- if (deletedAncestors)
- deletedAncestors.add(variableStatement);
- changes.deleteNode(sourceFile, variableStatement);
- }
- else {
- if (deletedAncestors)
- deletedAncestors.add(varDecl);
- changes.deleteNodeInList(sourceFile, varDecl);
- }
+ function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) {
+ if (mayDeleteParameter(p, checker, isFixAll)) {
+ changes.delete(sourceFile, p);
+ deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker);
}
}
function mayDeleteParameter(p, checker, isFixAll) {
var parent = p.parent;
switch (parent.kind) {
case 154 /* MethodDeclaration */:
- // Don't remove a parameter if this overrides something
+ // Don't remove a parameter if this overrides something.
var symbol = checker.getSymbolAtLocation(parent.name);
if (ts.isMemberSymbolInBaseType(symbol, checker))
return false;
// falls through
case 155 /* Constructor */:
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
- case 193 /* ArrowFunction */: {
- // Can't remove a non-last parameter. Can remove a parameter in code-fix-all if future parameters are also unused.
+ case 237 /* FunctionDeclaration */:
+ return true;
+ case 194 /* FunctionExpression */:
+ case 195 /* ArrowFunction */: {
+ // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused.
var parameters = parent.parameters;
var index = parameters.indexOf(p);
ts.Debug.assert(index !== -1);
@@ -104480,6 +105433,14 @@ var ts;
return ts.Debug.failBadSyntaxKind(parent);
}
}
+ function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) {
+ ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) {
+ var index = deletedParameter.parent.parameters.indexOf(deletedParameter);
+ if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments.
+ changes.delete(sourceFile, call.arguments[index]);
+ }
+ });
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -104499,12 +105460,12 @@ var ts;
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
});
function doChange(changes, sourceFile, start) {
- var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, start);
var statement = ts.findAncestor(token, ts.isStatement);
ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile));
var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent;
switch (container.kind) {
- case 217 /* IfStatement */:
+ case 220 /* IfStatement */:
if (container.elseStatement) {
if (ts.isBlock(statement.parent)) {
changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements));
@@ -104515,16 +105476,16 @@ var ts;
break;
}
// falls through
- case 219 /* WhileStatement */:
- case 220 /* ForStatement */:
- changes.deleteNode(sourceFile, container);
+ case 222 /* WhileStatement */:
+ case 223 /* ForStatement */:
+ changes.delete(sourceFile, container);
break;
default:
if (ts.isBlock(statement.parent)) {
split(sliceAfter(statement.parent.statements, statement), shouldRemove, function (start, end) { return changes.deleteNodeRange(sourceFile, start, end); });
}
else {
- changes.deleteNode(sourceFile, statement);
+ changes.delete(sourceFile, statement);
}
}
}
@@ -104536,12 +105497,12 @@ var ts;
}
function isPurelyTypeDeclaration(s) {
switch (s.kind) {
- case 236 /* InterfaceDeclaration */:
- case 237 /* TypeAliasDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
return true;
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
return ts.getModuleInstanceState(s) !== 1 /* Instantiated */;
- case 238 /* EnumDeclaration */:
+ case 241 /* EnumDeclaration */:
return ts.hasModifier(s, 2048 /* Const */);
default:
return false;
@@ -104575,7 +105536,7 @@ var ts;
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
});
function doChange(changes, sourceFile, start) {
- var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, start);
var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
var pos = token.getStart(sourceFile);
var statementPos = labeledStatement.statement.getStart(sourceFile);
@@ -104605,7 +105566,7 @@ var ts;
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 === 281 /* JSDocNullableType */) {
+ if (typeNode.kind === 284 /* 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, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -104625,7 +105586,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 281 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -104634,7 +105595,7 @@ var ts;
changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217
}
function getInfo(sourceFile, pos, checker) {
- var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer);
+ var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer);
var typeNode = decl && decl.type;
return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) };
}
@@ -104642,22 +105603,22 @@ var ts;
// NOTE: Some locations are not handled yet:
// MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments
switch (node.kind) {
- case 208 /* AsExpression */:
+ case 210 /* AsExpression */:
case 158 /* CallSignature */:
case 159 /* ConstructSignature */:
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
case 156 /* GetAccessor */:
case 160 /* IndexSignature */:
- case 177 /* MappedType */:
+ case 179 /* MappedType */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
case 149 /* Parameter */:
case 152 /* PropertyDeclaration */:
case 151 /* PropertySignature */:
case 157 /* SetAccessor */:
- case 237 /* TypeAliasDeclaration */:
- case 190 /* TypeAssertionExpression */:
- case 232 /* VariableDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 192 /* TypeAssertionExpression */:
+ case 235 /* VariableDeclaration */:
return true;
default:
return false;
@@ -104704,7 +105665,7 @@ var ts;
}
}
function getNodes(sourceFile, start) {
- var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, start);
var containingFunction = ts.getContainingFunction(token);
if (!containingFunction) {
return;
@@ -104714,11 +105675,11 @@ var ts;
case 154 /* MethodDeclaration */:
insertBefore = containingFunction.name;
break;
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile);
break;
- case 193 /* ArrowFunction */:
+ case 195 /* ArrowFunction */:
insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters);
break;
default:
@@ -104888,8 +105849,22 @@ var ts;
signatureDeclaration.body = body;
return signatureDeclaration;
}
- function createMethodFromCallExpression(_a, methodName, inJs, makeStatic, preferences) {
+ function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences) {
var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent;
+ var checker = context.program.getTypeChecker();
+ var types = ts.map(args, function (arg) {
+ var type = checker.getTypeAtLocation(arg);
+ if (type === undefined) {
+ return undefined;
+ }
+ // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
+ type = checker.getBaseTypeOfLiteralType(type);
+ return checker.typeToTypeNode(type);
+ });
+ var names = ts.map(args, function (arg) {
+ return ts.isIdentifier(arg) ? arg.text :
+ ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined;
+ });
return ts.createMethod(
/*decorators*/ undefined,
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined,
@@ -104898,11 +105873,11 @@ var ts;
/*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) {
return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i);
}),
- /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs),
+ /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs),
/*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences));
}
codefix.createMethodFromCallExpression = createMethodFromCallExpression;
- function createDummyParameters(argCount, names, minArgumentCount, inJs) {
+ function createDummyParameters(argCount, names, types, minArgumentCount, inJs) {
var parameters = [];
for (var i = 0; i < argCount; i++) {
var newParameter = ts.createParameter(
@@ -104911,7 +105886,7 @@ var ts;
/*dotDotDotToken*/ undefined,
/*name*/ names && names[i] || "arg" + i,
/*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined,
- /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */),
+ /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */),
/*initializer*/ undefined);
parameters.push(newParameter);
}
@@ -104937,7 +105912,7 @@ var ts;
}
var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0);
var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; });
- var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false);
+ var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false);
if (someSigHasRestParameter) {
var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */));
var restParameter = ts.createParameter(
@@ -105001,18 +105976,19 @@ var ts;
if (ts.isSourceFileJavaScript(sourceFile)) {
return undefined; // TODO: GH#20113
}
- var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, start);
var declaration;
var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); });
- return changes.length === 0 ? undefined
- : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getNameOfDeclaration(declaration).getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)];
+ var name = declaration && ts.getNameOfDeclaration(declaration);
+ return !name || changes.length === 0 ? undefined
+ : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)];
},
fixIds: [fixId],
getAllCodeActions: function (context) {
var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
var markSeen = ts.nodeSeenTracker();
return codefix.codeFixAll(context, errorCodes, function (changes, err) {
- doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen);
+ doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen);
});
},
});
@@ -105094,11 +106070,11 @@ var ts;
}
function isApplicableFunctionForInference(declaration) {
switch (declaration.kind) {
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
case 154 /* MethodDeclaration */:
case 155 /* Constructor */:
return true;
- case 192 /* FunctionExpression */:
+ case 194 /* FunctionExpression */:
return !!declaration.name;
}
return false;
@@ -105158,8 +106134,8 @@ var ts;
function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) {
switch (containingFunction.kind) {
case 155 /* Constructor */:
- case 192 /* FunctionExpression */:
- case 234 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
case 154 /* MethodDeclaration */:
var isConstructor = containingFunction.kind === 155 /* Constructor */;
var searchToken = isConstructor ?
@@ -105227,21 +106203,21 @@ var ts;
node = node.parent;
}
switch (node.parent.kind) {
- case 199 /* PostfixUnaryExpression */:
+ case 201 /* PostfixUnaryExpression */:
usageContext.isNumber = true;
break;
- case 198 /* PrefixUnaryExpression */:
+ case 200 /* PrefixUnaryExpression */:
inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext);
break;
- case 200 /* BinaryExpression */:
+ case 202 /* BinaryExpression */:
inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext);
break;
- case 266 /* CaseClause */:
- case 267 /* DefaultClause */:
+ case 269 /* CaseClause */:
+ case 270 /* DefaultClause */:
inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext);
break;
- case 187 /* CallExpression */:
- case 188 /* NewExpression */:
+ case 189 /* CallExpression */:
+ case 190 /* NewExpression */:
if (node.parent.expression === node) {
inferTypeFromCallExpressionContext(node.parent, checker, usageContext);
}
@@ -105249,13 +106225,13 @@ var ts;
inferTypeFromContextualType(node, checker, usageContext);
}
break;
- case 185 /* PropertyAccessExpression */:
+ case 187 /* PropertyAccessExpression */:
inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext);
break;
- case 186 /* ElementAccessExpression */:
+ case 188 /* ElementAccessExpression */:
inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext);
break;
- case 232 /* VariableDeclaration */: {
+ case 235 /* VariableDeclaration */: {
var _a = node.parent, name = _a.name, initializer = _a.initializer;
if (node === name) {
if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error.
@@ -105364,7 +106340,7 @@ var ts;
// LogicalOperator
case 54 /* BarBarToken */:
if (node === parent.left &&
- (node.parent.parent.kind === 232 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) {
+ (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) {
// var x = x || {};
// TODO: use getFalsyflagsOfType
addCandidateType(usageContext, checker.getTypeAtLocation(parent.right));
@@ -105392,7 +106368,7 @@ var ts;
}
}
inferTypeFromContext(parent, checker, callContext.returnType);
- if (parent.kind === 187 /* CallExpression */) {
+ if (parent.kind === 189 /* CallExpression */) {
(usageContext.callContexts || (usageContext.callContexts = [])).push(callContext);
}
else {
@@ -105560,8 +106536,8 @@ var ts;
});
function getActionsForUsageOfInvalidImport(context) {
var sourceFile = context.sourceFile;
- var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 187 /* CallExpression */ : 188 /* NewExpression */;
- var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
+ var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */;
+ var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
if (!node) {
return [];
}
@@ -105588,7 +106564,7 @@ var ts;
});
function getActionsForInvalidImportLocation(context) {
var sourceFile = context.sourceFile;
- var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
+ var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); });
if (!node) {
return [];
}
@@ -105663,7 +106639,7 @@ var ts;
},
});
function getPropertyDeclaration(sourceFile, pos) {
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined;
}
function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) {
@@ -105748,7 +106724,7 @@ var ts;
: ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required)));
}
function getInfo(sourceFile, pos) {
- var parent = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false).parent;
+ var parent = ts.getTokenAtPosition(sourceFile, pos).parent;
if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true))
throw ts.Debug.failBadSyntaxKind(parent);
var decl = ts.cast(parent.parent, ts.isVariableDeclaration);
@@ -105781,7 +106757,7 @@ var ts;
}); },
});
function getInfo(sourceFile, pos) {
- var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var name = ts.getTokenAtPosition(sourceFile, pos);
if (!ts.isIdentifier(name))
return undefined; // bad input
var parent = name.parent;
@@ -105805,7 +106781,7 @@ var ts;
(function (codefix) {
var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof";
var fixId = fixIdAddMissingTypeof;
- var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here.code];
+ var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code];
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
@@ -105820,9 +106796,9 @@ var ts;
}); },
});
function getImportTypeNode(sourceFile, pos) {
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
ts.Debug.assert(token.kind === 91 /* ImportKeyword */);
- ts.Debug.assert(token.parent.kind === 179 /* ImportType */);
+ ts.Debug.assert(token.parent.kind === 181 /* ImportType */);
return token.parent;
}
function doChange(changes, sourceFile, importType) {
@@ -105858,7 +106834,7 @@ var ts;
}); }
});
function getInfo(sourceFile, pos) {
- var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ var token = ts.getTokenAtPosition(sourceFile, pos);
var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration);
if (ts.isClassDeclaration(indexSignature.parent))
return undefined;
@@ -105887,129 +106863,325 @@ var ts;
(function (ts) {
var refactor;
(function (refactor) {
- var generateGetAccessorAndSetAccessor;
- (function (generateGetAccessorAndSetAccessor) {
- var refactorName = "Convert import";
- var actionNameNamespaceToNamed = "Convert namespace import to named imports";
- var actionNameNamedToNamespace = "Convert named imports to namespace import";
- refactor.registerRefactor(refactorName, {
- getAvailableActions: function (context) {
- var i = getImportToConvert(context);
- if (!i)
+ var refactorName = "Convert export";
+ var actionNameDefaultToNamed = "Convert default export to named export";
+ var actionNameNamedToDefault = "Convert named export to default export";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ var info = getInfo(context);
+ if (!info)
+ return undefined;
+ var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message;
+ var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault;
+ return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault);
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ },
+ });
+ function getInfo(context) {
+ var file = context.file;
+ var span = ts.getRefactorContextSpan(context);
+ var token = ts.getTokenAtPosition(file, span.start);
+ var exportNode = ts.getParentNodeInSpan(token, file, span);
+ if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) {
+ return undefined;
+ }
+ var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol;
+ var flags = ts.getModifierFlags(exportNode);
+ var wasDefault = !!(flags & 512 /* Default */);
+ // If source file already has a default export, don't offer refactor.
+ if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) {
+ return undefined;
+ }
+ switch (exportNode.kind) {
+ case 237 /* FunctionDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 242 /* ModuleDeclaration */: {
+ var node = exportNode;
+ return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
+ }
+ case 217 /* VariableStatement */: {
+ var vs = exportNode;
+ // Must be `export const x = something;`.
+ if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) {
return undefined;
- var description = i.kind === 246 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message;
- var actionName = i.kind === 246 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace;
- return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
- },
- getEditsForAction: function (context, actionName) {
- ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace);
- var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); });
- return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ var decl = ts.first(vs.declarationList.declarations);
+ if (!decl.initializer)
+ return undefined;
+ ts.Debug.assert(!wasDefault);
+ return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined;
+ }
+ default:
+ return undefined;
+ }
+ }
+ function doChange(exportingSourceFile, program, info, changes, cancellationToken) {
+ changeExport(exportingSourceFile, info, changes, program.getTypeChecker());
+ changeImports(program, info, changes, cancellationToken);
+ }
+ function changeExport(exportingSourceFile, _a, changes, checker) {
+ var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName;
+ if (wasDefault) {
+ changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */)));
+ }
+ else {
+ var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */));
+ switch (exportNode.kind) {
+ case 237 /* FunctionDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */));
+ break;
+ case 217 /* VariableStatement */:
+ // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;`
+ if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) {
+ // We checked in `getInfo` that an initializer exists.
+ changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer)));
+ break;
+ }
+ // falls through
+ case 241 /* EnumDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ // `export type T = number;` -> `type T = number; export default T;`
+ changes.deleteModifier(exportingSourceFile, exportKeyword);
+ changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text)));
+ break;
+ default:
+ ts.Debug.assertNever(exportNode);
+ }
+ }
+ }
+ function changeImports(program, _a, changes, cancellationToken) {
+ var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol;
+ var checker = program.getTypeChecker();
+ var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName));
+ ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) {
+ var importingSourceFile = ref.getSourceFile();
+ if (wasDefault) {
+ changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text);
+ }
+ else {
+ changeNamedToDefaultImport(importingSourceFile, ref, changes);
}
});
- // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`.
- function getImportToConvert(context) {
- var file = context.file;
- var span = ts.getRefactorContextSpan(context);
- var token = ts.getTokenAtPosition(file, span.start, /*includeJsDocComment*/ false);
- var importDecl = ts.getParentNodeInSpan(token, file, span);
- if (!importDecl || !ts.isImportDeclaration(importDecl))
- return undefined;
- var importClause = importDecl.importClause;
- return importClause && importClause.namedBindings;
- }
- function doChange(sourceFile, program, changes, toConvert) {
- var checker = program.getTypeChecker();
- if (toConvert.kind === 246 /* NamespaceImport */) {
- doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()));
+ }
+ function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) {
+ var parent = ref.parent;
+ switch (parent.kind) {
+ case 187 /* PropertyAccessExpression */:
+ // `a.default` --> `a.foo`
+ changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName));
+ break;
+ case 251 /* ImportSpecifier */:
+ case 255 /* ExportSpecifier */: {
+ var spec = parent;
+ // `default as foo` --> `foo`, `default as bar` --> `foo as bar`
+ changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text));
+ break;
}
- else {
- doChangeNamedToNamespace(sourceFile, checker, changes, toConvert);
- }
- }
- function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
- var usedAsNamespaceOrDefault = false;
- var nodesToReplace = [];
- var conflictingNames = ts.createMap();
- ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) {
- if (!ts.isPropertyAccessExpression(id.parent)) {
- usedAsNamespaceOrDefault = true;
+ case 248 /* ImportClause */: {
+ var clause = parent;
+ ts.Debug.assert(clause.name === ref);
+ var spec = makeImportSpecifier(exportName, ref.text);
+ var namedBindings = clause.namedBindings;
+ if (!namedBindings) {
+ // `import foo from "./a";` --> `import { foo } from "./a";`
+ changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec]));
+ }
+ else if (namedBindings.kind === 249 /* NamespaceImport */) {
+ // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";`
+ changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) });
+ var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */;
+ var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference);
+ changes.insertNodeAfter(importingSourceFile, clause.parent, newImport);
}
else {
- var parent = ts.cast(id.parent, ts.isPropertyAccessExpression);
- var exportName = parent.name.text;
- if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) {
- conflictingNames.set(exportName, true);
- }
- ts.Debug.assert(parent.expression === id);
- nodesToReplace.push(parent);
+ // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";`
+ changes.delete(importingSourceFile, ref);
+ changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec);
}
- });
- // We may need to change `mod.x` to `_x` to avoid a name conflict.
- var exportNameToImportName = ts.createMap();
- for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) {
- var propertyAccess = nodesToReplace_1[_i];
- var exportName = propertyAccess.name.text;
- var importName = exportNameToImportName.get(exportName);
- if (importName === undefined) {
- exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName);
- }
- changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName));
- }
- var importSpecifiers = [];
- exportNameToImportName.forEach(function (name, propertyName) {
- importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)));
- });
- var importDecl = toConvert.parent.parent;
- if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) {
- // Need to leave the namespace import alone
- changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers));
- }
- else {
- changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers));
+ break;
}
+ default:
+ ts.Debug.failBadSyntaxKind(parent);
}
- 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 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);
- }) || false;
- });
- var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
- var neededNamedImports = [];
- var _loop_11 = function (element) {
- var propertyName = (element.propertyName || element.name).text;
- ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
- var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
- if (ts.isShorthandPropertyAssignment(id.parent)) {
- changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access));
- }
- else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) {
- if (!neededNamedImports.some(function (n) { return n.name === element.name; })) {
- neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text)));
- }
+ }
+ function changeNamedToDefaultImport(importingSourceFile, ref, changes) {
+ var parent = ref.parent;
+ switch (parent.kind) {
+ case 187 /* PropertyAccessExpression */:
+ // `a.foo` --> `a.default`
+ changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default"));
+ break;
+ case 251 /* ImportSpecifier */:
+ case 255 /* ExportSpecifier */: {
+ var spec = parent;
+ if (spec.kind === 251 /* ImportSpecifier */) {
+ // `import { foo } from "./a";` --> `import foo from "./a";`
+ // `import { foo as bar } from "./a";` --> `import bar from "./a";`
+ var defaultImport = ts.createIdentifier(spec.name.text);
+ if (spec.parent.elements.length === 1) {
+ changes.replaceNode(importingSourceFile, spec.parent, defaultImport);
}
else {
- changes.replaceNode(sourceFile, id, access);
+ changes.delete(importingSourceFile, spec);
+ changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport);
}
- });
- };
- for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
- var element = _a[_i];
- _loop_11(element);
+ }
+ else {
+ // `export { foo } from "./a";` --> `export { default as foo } from "./a";`
+ // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";`
+ // `export { foo as default } from "./a";` --> `export { default } from "./a";`
+ // (Because `export foo from "./a";` isn't valid syntax.)
+ changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text));
+ }
+ break;
}
- changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
- if (neededNamedImports.length) {
- changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports));
+ default:
+ ts.Debug.failBadSyntaxKind(parent);
+ }
+ }
+ function makeImportSpecifier(propertyName, name) {
+ return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
+ }
+ function makeExportSpecifier(propertyName, name) {
+ return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name));
+ }
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var refactorName = "Convert import";
+ var actionNameNamespaceToNamed = "Convert namespace import to named imports";
+ var actionNameNamedToNamespace = "Convert named imports to namespace import";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ var i = getImportToConvert(context);
+ if (!i)
+ return undefined;
+ var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message;
+ var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace;
+ return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace);
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ });
+ // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`.
+ function getImportToConvert(context) {
+ var file = context.file;
+ var span = ts.getRefactorContextSpan(context);
+ var token = ts.getTokenAtPosition(file, span.start);
+ var importDecl = ts.getParentNodeInSpan(token, file, span);
+ if (!importDecl || !ts.isImportDeclaration(importDecl))
+ return undefined;
+ var importClause = importDecl.importClause;
+ return importClause && importClause.namedBindings;
+ }
+ function doChange(sourceFile, program, changes, toConvert) {
+ var checker = program.getTypeChecker();
+ if (toConvert.kind === 249 /* NamespaceImport */) {
+ doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()));
+ }
+ else {
+ doChangeNamedToNamespace(sourceFile, checker, changes, toConvert);
+ }
+ }
+ function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) {
+ var usedAsNamespaceOrDefault = false;
+ var nodesToReplace = [];
+ var conflictingNames = ts.createMap();
+ ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) {
+ if (!ts.isPropertyAccessExpression(id.parent)) {
+ usedAsNamespaceOrDefault = true;
}
+ else {
+ var parent = ts.cast(id.parent, ts.isPropertyAccessExpression);
+ var exportName = parent.name.text;
+ if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) {
+ conflictingNames.set(exportName, true);
+ }
+ ts.Debug.assert(parent.expression === id);
+ nodesToReplace.push(parent);
+ }
+ });
+ // We may need to change `mod.x` to `_x` to avoid a name conflict.
+ var exportNameToImportName = ts.createMap();
+ for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) {
+ var propertyAccess = nodesToReplace_1[_i];
+ var exportName = propertyAccess.name.text;
+ var importName = exportNameToImportName.get(exportName);
+ if (importName === undefined) {
+ exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName);
+ }
+ changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName));
}
- function updateImport(old, defaultImportName, elements) {
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier);
+ var importSpecifiers = [];
+ exportNameToImportName.forEach(function (name, propertyName) {
+ importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)));
+ });
+ var importDecl = toConvert.parent.parent;
+ if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) {
+ // Need to leave the namespace import alone
+ changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers));
}
- })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
+ else {
+ changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers));
+ }
+ }
+ 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 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);
+ }) || false;
+ });
+ var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
+ var neededNamedImports = [];
+ var _loop_13 = function (element) {
+ var propertyName = (element.propertyName || element.name).text;
+ ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
+ var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
+ if (ts.isShorthandPropertyAssignment(id.parent)) {
+ changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access));
+ }
+ else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) {
+ if (!neededNamedImports.some(function (n) { return n.name === element.name; })) {
+ neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text)));
+ }
+ }
+ else {
+ changes.replaceNode(sourceFile, id, access);
+ }
+ });
+ };
+ for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
+ var element = _a[_i];
+ _loop_13(element);
+ }
+ changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
+ if (neededNamedImports.length) {
+ changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports));
+ }
+ }
+ function updateImport(old, defaultImportName, elements) {
+ return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier);
+ }
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
/* @internal */
@@ -106167,7 +107339,7 @@ var ts;
}
// Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.
// This may fail (e.g. you select two statements in the root of a source file)
- var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false), sourceFile, span);
+ var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span);
// Do the same for the ending position
var end = ts.getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span);
var declarations = [];
@@ -106320,7 +107492,7 @@ var ts;
return true;
}
if (ts.isDeclaration(node)) {
- var declaringNode = (node.kind === 232 /* VariableDeclaration */) ? node.parent.parent : node;
+ var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node;
if (ts.hasModifier(declaringNode, 1 /* Export */)) {
// TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`)
// Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`!
@@ -106332,13 +107504,13 @@ var ts;
}
// Some things can't be extracted in certain situations
switch (node.kind) {
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
(errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport));
return true;
case 97 /* SuperKeyword */:
// For a super *constructor call*, we have to be extracting the entire class,
// but a super *method call* simply implies a 'this' reference
- if (node.parent.kind === 187 /* CallExpression */) {
+ if (node.parent.kind === 189 /* CallExpression */) {
// Super constructor call
var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217
if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) {
@@ -106353,8 +107525,8 @@ var ts;
}
if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) {
switch (node.kind) {
- case 234 /* FunctionDeclaration */:
- case 235 /* ClassDeclaration */:
+ case 237 /* FunctionDeclaration */:
+ case 238 /* ClassDeclaration */:
if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) {
// You cannot extract global declarations
(errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
@@ -106366,20 +107538,20 @@ var ts;
}
var savedPermittedJumps = permittedJumps;
switch (node.kind) {
- case 217 /* IfStatement */:
+ case 220 /* IfStatement */:
permittedJumps = 0 /* None */;
break;
- case 230 /* TryStatement */:
+ case 233 /* TryStatement */:
// forbid all jumps inside try blocks
permittedJumps = 0 /* None */;
break;
- case 213 /* Block */:
- if (node.parent && node.parent.kind === 230 /* TryStatement */ && node.parent.finallyBlock === node) {
+ case 216 /* Block */:
+ if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) {
// allow unconditional returns from finally blocks
permittedJumps = 4 /* Return */;
}
break;
- case 266 /* CaseClause */:
+ case 269 /* CaseClause */:
// allow unlabeled break inside case clauses
permittedJumps |= 1 /* Break */;
break;
@@ -106391,11 +107563,11 @@ var ts;
break;
}
switch (node.kind) {
- case 174 /* ThisType */:
+ case 176 /* ThisType */:
case 99 /* ThisKeyword */:
rangeFacts |= RangeFacts.UsesThis;
break;
- case 228 /* LabeledStatement */:
+ case 231 /* LabeledStatement */:
{
var label = node.label;
(seenLabels || (seenLabels = [])).push(label.escapedText);
@@ -106403,8 +107575,8 @@ var ts;
seenLabels.pop();
break;
}
- case 224 /* BreakStatement */:
- case 223 /* ContinueStatement */:
+ case 227 /* BreakStatement */:
+ case 226 /* ContinueStatement */:
{
var label = node.label;
if (label) {
@@ -106414,20 +107586,20 @@ var ts;
}
}
else {
- if (!(permittedJumps & (node.kind === 224 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
+ if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) {
// attempt to break or continue in a forbidden context
(errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
}
}
break;
}
- case 197 /* AwaitExpression */:
+ case 199 /* AwaitExpression */:
rangeFacts |= RangeFacts.IsAsyncFunction;
break;
- case 203 /* YieldExpression */:
+ case 205 /* YieldExpression */:
rangeFacts |= RangeFacts.IsGenerator;
break;
- case 225 /* ReturnStatement */:
+ case 228 /* ReturnStatement */:
if (permittedJumps & 4 /* Return */) {
rangeFacts |= RangeFacts.HasReturn;
}
@@ -106492,7 +107664,7 @@ var ts;
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 274 /* SourceFile */) {
+ if (current.kind === 277 /* SourceFile */) {
return scopes;
}
}
@@ -106584,12 +107756,12 @@ var ts;
switch (scope.kind) {
case 155 /* Constructor */:
return "constructor";
- case 192 /* FunctionExpression */:
- case 234 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
return scope.name
? "function '" + scope.name.text + "'"
: "anonymous function";
- case 193 /* ArrowFunction */:
+ case 195 /* ArrowFunction */:
return "arrow function";
case 154 /* MethodDeclaration */:
return "method '" + scope.name.getText();
@@ -106602,12 +107774,12 @@ var ts;
}
}
function getDescriptionForClassLikeDeclaration(scope) {
- return scope.kind === 235 /* ClassDeclaration */
+ return scope.kind === 238 /* ClassDeclaration */
? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration"
: scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression";
}
function getDescriptionForModuleLikeDeclaration(scope) {
- return scope.kind === 240 /* ModuleBlock */
+ return scope.kind === 243 /* ModuleBlock */
? "namespace '" + scope.parent.name.getText() + "'"
: scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */;
}
@@ -106886,7 +108058,7 @@ var ts;
var localReference = ts.createIdentifier(localNameText);
changeTracker.replaceNode(context.file, node, localReference);
}
- else if (node.parent.kind === 216 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) {
+ else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) {
// If the parent is an expression statement and the target scope is the immediately enclosing one,
// replace the statement with the declaration.
var newVariableStatement = ts.createVariableStatement(
@@ -106905,9 +108077,9 @@ var ts;
changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false);
}
// Consume
- if (node.parent.kind === 216 /* ExpressionStatement */) {
+ if (node.parent.kind === 219 /* ExpressionStatement */) {
// If the parent is an expression statement, delete it.
- changeTracker.deleteNode(context.file, node.parent, ts.textChanges.useNonAdjustedPositions);
+ changeTracker.delete(context.file, node.parent);
}
else {
var localReference = ts.createIdentifier(localNameText);
@@ -106992,7 +108164,7 @@ var ts;
return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined };
}
function visitor(node) {
- if (!ignoreReturns && node.kind === 225 /* ReturnStatement */ && hasWritesOrVariableDeclarations) {
+ if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) {
var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
if (node.expression) {
if (!returnValueProperty) {
@@ -107170,7 +108342,7 @@ var ts;
var scope = scopes_1[_i];
usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() });
substitutionsPerScope.push(ts.createMap());
- functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 234 /* FunctionDeclaration */
+ functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */
? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)]
: []);
var constantErrors = [];
@@ -107233,7 +108405,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_12 = function (i) {
+ var _loop_14 = function (i) {
var scopeUsages = usagesPerScope[i];
// Special case: in the innermost scope, all usages are available.
// (The computed value reflects the value at the top-level of the scope, but the
@@ -107273,7 +108445,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_12(i);
+ _loop_14(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -107486,30 +108658,30 @@ var ts;
function isExtractableExpression(node) {
var parent = node.parent;
switch (parent.kind) {
- case 273 /* EnumMember */:
+ case 276 /* EnumMember */:
return false;
}
switch (node.kind) {
case 9 /* StringLiteral */:
- return parent.kind !== 244 /* ImportDeclaration */ &&
- parent.kind !== 248 /* ImportSpecifier */;
- case 204 /* SpreadElement */:
- case 180 /* ObjectBindingPattern */:
- case 182 /* BindingElement */:
+ return parent.kind !== 247 /* ImportDeclaration */ &&
+ parent.kind !== 251 /* ImportSpecifier */;
+ case 206 /* SpreadElement */:
+ case 182 /* ObjectBindingPattern */:
+ case 184 /* BindingElement */:
return false;
case 71 /* Identifier */:
- return parent.kind !== 182 /* BindingElement */ &&
- parent.kind !== 248 /* ImportSpecifier */ &&
- parent.kind !== 252 /* ExportSpecifier */;
+ return parent.kind !== 184 /* BindingElement */ &&
+ parent.kind !== 251 /* ImportSpecifier */ &&
+ parent.kind !== 255 /* ExportSpecifier */;
}
return true;
}
function isBlockLike(node) {
switch (node.kind) {
- case 213 /* Block */:
- case 274 /* SourceFile */:
- case 240 /* ModuleBlock */:
- case 266 /* CaseClause */:
+ case 216 /* Block */:
+ case 277 /* SourceFile */:
+ case 243 /* ModuleBlock */:
+ case 269 /* CaseClause */:
return true;
default:
return false;
@@ -107529,8 +108701,7 @@ var ts;
var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message;
refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
function getAvailableActions(context) {
- var file = context.file;
- if (!getConvertibleFieldAtPosition(context, file))
+ if (!getConvertibleFieldAtPosition(context))
return undefined;
return [{
name: actionName,
@@ -107545,7 +108716,7 @@ var ts;
}
function getEditsForAction(context, _actionName) {
var file = context.file;
- var fieldInfo = getConvertibleFieldAtPosition(context, file);
+ var fieldInfo = getConvertibleFieldAtPosition(context);
if (!fieldInfo)
return undefined;
var isJS = ts.isSourceFileJavaScript(file);
@@ -107606,13 +108777,13 @@ var ts;
function startsWithUnderscore(name) {
return name.charCodeAt(0) === 95 /* _ */;
}
- function getConvertibleFieldAtPosition(context, file) {
- var startPosition = context.startPosition, endPosition = context.endPosition;
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
+ function getConvertibleFieldAtPosition(context) {
+ var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition;
+ var node = ts.getTokenAtPosition(file, startPosition);
var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
// make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
- if (!declaration || !ts.rangeOverlapsWithStartEnd(declaration.name, startPosition, endPosition) // TODO: GH#18217
+ if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217
|| !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
return undefined;
var name = declaration.name.text;
@@ -107767,11 +108938,11 @@ var ts;
}
function isPureImport(node) {
switch (node.kind) {
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
return true;
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return !ts.hasModifier(node, 1 /* Export */);
- case 214 /* VariableStatement */:
+ case 217 /* VariableStatement */:
return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
default:
return false;
@@ -107824,10 +108995,10 @@ var ts;
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_13 = function (sourceFile) {
+ var _loop_15 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_14 = function (statement) {
+ var _loop_16 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -107849,22 +109020,22 @@ var ts;
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_14(statement);
+ _loop_16(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_13(sourceFile);
+ _loop_15(sourceFile);
}
}
function getNamespaceLikeImport(node) {
switch (node.kind) {
- case 244 /* ImportDeclaration */:
- return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 246 /* NamespaceImport */ ?
+ case 247 /* ImportDeclaration */:
+ return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ?
node.importClause.namedBindings.name : undefined;
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return node.name;
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
return ts.tryCast(node.name, ts.isIdentifier);
default:
return ts.Debug.assertNever(node);
@@ -107895,20 +109066,20 @@ var ts;
var newNamespaceId = ts.createIdentifier(newNamespaceName);
var newModuleString = ts.createLiteral(newModuleSpecifier);
switch (node.kind) {
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
return ts.createImportDeclaration(
/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString);
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString));
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString));
default:
return ts.Debug.assertNever(node);
}
}
function moduleSpecifierFromImport(i) {
- return (i.kind === 244 /* ImportDeclaration */ ? i.moduleSpecifier
- : i.kind === 243 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
+ return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier
+ : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
: i.initializer.arguments[0]);
}
function forEachImportInStatement(statement, cb) {
@@ -107978,15 +109149,15 @@ var ts;
}
function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
switch (importDecl.kind) {
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
break;
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
if (isUnused(importDecl.name)) {
- changes.deleteNode(sourceFile, importDecl);
+ changes.delete(sourceFile, importDecl);
}
break;
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
break;
default:
@@ -107999,23 +109170,23 @@ var ts;
var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
var defaultUnused = !name || isUnused(name);
var namedBindingsUnused = !namedBindings ||
- (namedBindings.kind === 246 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
+ (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
if (defaultUnused && namedBindingsUnused) {
- changes.deleteNode(sourceFile, importDecl);
+ changes.delete(sourceFile, importDecl);
}
else {
if (name && defaultUnused) {
- changes.deleteNode(sourceFile, name);
+ changes.delete(sourceFile, name);
}
if (namedBindings) {
if (namedBindingsUnused) {
- changes.deleteNode(sourceFile, namedBindings);
+ changes.delete(sourceFile, namedBindings);
}
- else if (namedBindings.kind === 247 /* NamedImports */) {
+ else if (namedBindings.kind === 250 /* NamedImports */) {
for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
var element = _b[_i];
if (isUnused(element.name))
- changes.deleteNodeInList(sourceFile, element);
+ changes.delete(sourceFile, element);
}
}
}
@@ -108026,20 +109197,20 @@ var ts;
switch (name.kind) {
case 71 /* Identifier */:
if (isUnused(name)) {
- changes.deleteNode(sourceFile, name);
+ changes.delete(sourceFile, name);
}
break;
- case 181 /* ArrayBindingPattern */:
+ case 183 /* ArrayBindingPattern */:
break;
- case 180 /* ObjectBindingPattern */:
+ case 182 /* ObjectBindingPattern */:
if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
- changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
+ changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
}
else {
for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
var element = _a[_i];
if (ts.isIdentifier(element.name) && isUnused(element.name)) {
- changes.deleteNode(sourceFile, element.name);
+ changes.delete(sourceFile, element.name);
}
}
}
@@ -108136,13 +109307,13 @@ var ts;
// Below should all be utilities
function isInImport(decl) {
switch (decl.kind) {
- case 243 /* ImportEqualsDeclaration */:
- case 248 /* ImportSpecifier */:
- case 245 /* ImportClause */:
+ case 246 /* ImportEqualsDeclaration */:
+ case 251 /* ImportSpecifier */:
+ case 248 /* ImportClause */:
return true;
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
return isVariableDeclarationInImport(decl);
- case 182 /* BindingElement */:
+ case 184 /* BindingElement */:
return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
default:
return false;
@@ -108154,7 +109325,7 @@ var ts;
}
function filterImport(i, moduleSpecifier, keep) {
switch (i.kind) {
- case 244 /* ImportDeclaration */: {
+ case 247 /* ImportDeclaration */: {
var clause = i.importClause;
if (!clause)
return undefined;
@@ -108164,9 +109335,9 @@ var ts;
? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
: undefined;
}
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return keep(i.name) ? i : undefined;
- case 232 /* VariableDeclaration */: {
+ case 235 /* VariableDeclaration */: {
var name = filterBindingName(i.name, keep);
return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
}
@@ -108175,7 +109346,7 @@ var ts;
}
}
function filterNamedBindings(namedBindings, keep) {
- if (namedBindings.kind === 246 /* NamespaceImport */) {
+ if (namedBindings.kind === 249 /* NamespaceImport */) {
return keep(namedBindings.name) ? namedBindings : undefined;
}
else {
@@ -108187,9 +109358,9 @@ var ts;
switch (name.kind) {
case 71 /* Identifier */:
return keep(name) ? name : undefined;
- case 181 /* ArrayBindingPattern */:
+ case 183 /* ArrayBindingPattern */:
return name;
- case 180 /* ObjectBindingPattern */: {
+ case 182 /* ObjectBindingPattern */: {
// We can't handle nested destructurings or property names well here, so just copy them all.
var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
@@ -108246,13 +109417,13 @@ var ts;
}
function isNonVariableTopLevelDeclaration(node) {
switch (node.kind) {
- case 234 /* FunctionDeclaration */:
- case 235 /* ClassDeclaration */:
- case 239 /* ModuleDeclaration */:
- case 238 /* EnumDeclaration */:
- case 237 /* TypeAliasDeclaration */:
- case 236 /* InterfaceDeclaration */:
- case 243 /* ImportEqualsDeclaration */:
+ case 237 /* FunctionDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return true;
default:
return false;
@@ -108260,17 +109431,17 @@ var ts;
}
function forEachTopLevelDeclaration(statement, cb) {
switch (statement.kind) {
- case 234 /* FunctionDeclaration */:
- case 235 /* ClassDeclaration */:
- case 239 /* ModuleDeclaration */:
- case 238 /* EnumDeclaration */:
- case 237 /* TypeAliasDeclaration */:
- case 236 /* InterfaceDeclaration */:
- case 243 /* ImportEqualsDeclaration */:
+ case 237 /* FunctionDeclaration */:
+ case 238 /* ClassDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return cb(statement);
- case 214 /* VariableStatement */:
+ case 217 /* VariableStatement */:
return ts.forEach(statement.declarationList.declarations, cb);
- case 216 /* ExpressionStatement */: {
+ case 219 /* ExpressionStatement */: {
var expression = statement.expression;
return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */
? cb(statement)
@@ -108279,7 +109450,7 @@ var ts;
}
}
function nameOfTopLevelDeclaration(d) {
- return d.kind === 216 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
+ return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
}
function getTopLevelDeclarationStatement(d) {
return ts.isVariableDeclaration(d) ? d.parent.parent : d;
@@ -108311,23 +109482,23 @@ var ts;
function addEs6Export(d) {
var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
switch (d.kind) {
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
- case 235 /* ClassDeclaration */:
+ case 238 /* ClassDeclaration */:
return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
- case 214 /* VariableStatement */:
+ case 217 /* VariableStatement */:
return ts.updateVariableStatement(d, modifiers, d.declarationList);
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
- case 238 /* EnumDeclaration */:
+ case 241 /* EnumDeclaration */:
return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
- case 237 /* TypeAliasDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
- case 236 /* InterfaceDeclaration */:
+ case 239 /* InterfaceDeclaration */:
return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
- case 216 /* ExpressionStatement */:
+ case 219 /* ExpressionStatement */:
return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
default:
return ts.Debug.assertNever(d);
@@ -108338,18 +109509,18 @@ var ts;
}
function getNamesToExportInCommonJS(decl) {
switch (decl.kind) {
- case 234 /* FunctionDeclaration */:
- case 235 /* ClassDeclaration */:
+ case 237 /* FunctionDeclaration */:
+ case 238 /* ClassDeclaration */:
return [decl.name.text]; // TODO: GH#18217
- case 214 /* VariableStatement */:
+ case 217 /* VariableStatement */:
return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
- case 239 /* ModuleDeclaration */:
- case 238 /* EnumDeclaration */:
- case 237 /* TypeAliasDeclaration */:
- case 236 /* InterfaceDeclaration */:
- case 243 /* ImportEqualsDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
return ts.emptyArray;
- case 216 /* ExpressionStatement */:
+ case 219 /* ExpressionStatement */:
return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
default:
return ts.Debug.assertNever(decl);
@@ -108424,7 +109595,7 @@ var ts;
return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression);
}
function getConvertibleArrowFunctionAtPosition(file, startPosition) {
- var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
+ var node = ts.getTokenAtPosition(file, startPosition);
var func = ts.getContainingFunction(node);
if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node)))
return undefined;
@@ -108530,7 +109701,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 278 /* FirstJSDocNode */ || kid.kind > 299 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 302 /* LastJSDocNode */; });
return child.kind < 146 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -108600,7 +109771,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(300 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(303 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
@@ -108657,7 +109828,7 @@ var ts;
return undefined; // TODO: GH#18217
};
TokenOrIdentifierObject.prototype.getChildren = function () {
- return ts.emptyArray;
+ return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function () {
return undefined;
@@ -108911,7 +110082,7 @@ var ts;
};
SourceFileObject.prototype.computeNamedDeclarations = function () {
var result = ts.createMultiMap();
- ts.forEachChild(this, visit);
+ this.forEachChild(visit);
return result;
function addDeclaration(declaration) {
var name = getDeclarationName(declaration);
@@ -108927,14 +110098,14 @@ var ts;
return declarations;
}
function getDeclarationName(declaration) {
- var name = ts.getNameOfDeclaration(declaration);
+ var name = ts.getNonAssignedNameOfDeclaration(declaration);
return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text
: ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined);
}
function visit(node) {
switch (node.kind) {
- case 234 /* FunctionDeclaration */:
- case 192 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
+ case 194 /* FunctionExpression */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
var functionDeclaration = node;
@@ -108956,17 +110127,17 @@ var ts;
}
ts.forEachChild(node, visit);
break;
- case 235 /* ClassDeclaration */:
- case 205 /* ClassExpression */:
- case 236 /* InterfaceDeclaration */:
- case 237 /* TypeAliasDeclaration */:
- case 238 /* EnumDeclaration */:
- case 239 /* ModuleDeclaration */:
- case 243 /* ImportEqualsDeclaration */:
- case 252 /* ExportSpecifier */:
- case 248 /* ImportSpecifier */:
- case 245 /* ImportClause */:
- case 246 /* NamespaceImport */:
+ case 238 /* ClassDeclaration */:
+ case 207 /* ClassExpression */:
+ case 239 /* InterfaceDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 242 /* ModuleDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
+ case 255 /* ExportSpecifier */:
+ case 251 /* ImportSpecifier */:
+ case 248 /* ImportClause */:
+ case 249 /* NamespaceImport */:
case 156 /* GetAccessor */:
case 157 /* SetAccessor */:
case 166 /* TypeLiteral */:
@@ -108979,8 +110150,8 @@ var ts;
break;
}
// falls through
- case 232 /* VariableDeclaration */:
- case 182 /* BindingElement */: {
+ case 235 /* VariableDeclaration */:
+ case 184 /* BindingElement */: {
var decl = node;
if (ts.isBindingPattern(decl.name)) {
ts.forEachChild(decl.name, visit);
@@ -108991,31 +110162,31 @@ var ts;
}
}
// falls through
- case 273 /* EnumMember */:
+ case 276 /* EnumMember */:
case 152 /* PropertyDeclaration */:
case 151 /* PropertySignature */:
addDeclaration(node);
break;
- case 250 /* ExportDeclaration */:
+ case 253 /* ExportDeclaration */:
// Handle named exports case e.g.:
// export {a, b as B} from "mod";
if (node.exportClause) {
ts.forEach(node.exportClause.elements, visit);
}
break;
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
var importClause = node.importClause;
if (importClause) {
// Handle default import case e.g.:
// import d from "mod";
if (importClause.name) {
- addDeclaration(importClause);
+ addDeclaration(importClause.name);
}
// Handle named bindings in imports e.g.:
// import * as NS from "mod";
// import {a, b as B} from "mod";
if (importClause.namedBindings) {
- if (importClause.namedBindings.kind === 246 /* NamespaceImport */) {
+ if (importClause.namedBindings.kind === 249 /* NamespaceImport */) {
addDeclaration(importClause.namedBindings);
}
else {
@@ -109024,7 +110195,7 @@ var ts;
}
}
break;
- case 200 /* BinaryExpression */:
+ case 202 /* BinaryExpression */:
if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) {
addDeclaration(node);
}
@@ -109392,7 +110563,7 @@ var ts;
readFile: function (fileName) {
// stub missing host functionality
var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
- var entry = hostCache.getEntryByPath(path);
+ var entry = hostCache && hostCache.getEntryByPath(path);
if (entry) {
return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot);
}
@@ -109442,7 +110613,7 @@ var ts;
return;
function fileExists(fileName) {
var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
- var entry = hostCache.getEntryByPath(path);
+ var entry = hostCache && hostCache.getEntryByPath(path);
return entry ?
!ts.isString(entry) :
(!!host.fileExists && host.fileExists(fileName));
@@ -109457,11 +110628,11 @@ var ts;
return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile);
}
function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) {
- ts.Debug.assert(hostCache !== undefined);
+ ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");
// The program is asking for this file, check first if the host can locate it.
// If the host can not locate the file, then it does not exist. return undefined
// to the program to allow reporting of errors for missing files.
- var hostFileInformation = hostCache.getOrCreateEntryByPath(fileName, path);
+ var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path);
if (!hostFileInformation) {
return undefined;
}
@@ -109557,17 +110728,17 @@ var ts;
return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken));
}
function getCompletionsAtPosition(fileName, position, options) {
- if (options === void 0) { options = ts.defaultPreferences; }
+ if (options === void 0) { options = ts.emptyOptions; }
// Convert from deprecated options names to new names
var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions });
synchronizeHostData();
return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter);
}
function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) {
- if (preferences === void 0) { preferences = ts.defaultPreferences; }
+ if (preferences === void 0) { preferences = ts.emptyOptions; }
synchronizeHostData();
return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217
- getCanonicalFileName, preferences, cancellationToken);
+ preferences, cancellationToken);
}
function getCompletionEntrySymbol(fileName, position, name, source) {
synchronizeHostData();
@@ -109592,10 +110763,10 @@ var ts;
return undefined;
}
// falls through
- case 185 /* PropertyAccessExpression */:
+ case 187 /* PropertyAccessExpression */:
case 146 /* QualifiedName */:
case 99 /* ThisKeyword */:
- case 174 /* ThisType */:
+ case 176 /* ThisType */:
case 97 /* SuperKeyword */:
// For the identifiers/this/super etc get the type at position
var type_1 = typeChecker.getTypeAtLocation(node);
@@ -109640,7 +110811,8 @@ var ts;
return file.getLineAndCharacterOfPosition(position);
}
// Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M])
- var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm;
+ var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/;
+ var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
function scanForSourcemapURL(fileName) {
var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
@@ -109649,11 +110821,15 @@ var ts;
}
var starts = ts.getLineStarts(mappedFile);
for (var index = starts.length - 1; index >= 0; index--) {
- sourceMapCommentRegExp.lastIndex = starts[index];
- var comment = sourceMapCommentRegExp.exec(mappedFile.text);
+ var lineText = mappedFile.text.substring(starts[index], starts[index + 1]);
+ var comment = sourceMapCommentRegExp.exec(lineText);
if (comment) {
return comment[1];
}
+ // If we see a nonwhitespace/map comment-like line, break, to avoid scanning up the entire file
+ else if (!lineText.match(whitespaceOrMapCommentRegExp)) {
+ break;
+ }
}
}
function convertDocumentToSourceMapper(file, contents, mapFileName) {
@@ -109807,18 +110983,32 @@ var ts;
return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
}
function findRenameLocations(fileName, position, findInStrings, findInComments) {
- return getReferences(fileName, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true });
+ synchronizeHostData();
+ var sourceFile = getValidSourceFile(fileName);
+ var node = ts.getTouchingPropertyName(sourceFile, position);
+ if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) {
+ var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement;
+ return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); });
+ }
+ else {
+ var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true });
+ return refs && refs.map(function (_a) {
+ var fileName = _a.fileName, textSpan = _a.textSpan;
+ return ({ fileName: fileName, textSpan: textSpan });
+ });
+ }
}
function getReferencesAtPosition(fileName, position) {
- return getReferences(fileName, position);
+ synchronizeHostData();
+ return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position);
}
- function getReferences(fileName, position, options) {
+ function getReferences(node, position, options) {
synchronizeHostData();
// Exclude default library when renaming as commonly user don't want to change that file.
var sourceFiles = options && options.isForRename
? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); })
: program.getSourceFiles();
- return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options);
+ return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options);
}
function findReferences(fileName, position) {
synchronizeHostData();
@@ -109842,10 +111032,11 @@ var ts;
/**
* This is a semantic operation.
*/
- function getSignatureHelpItems(fileName, position) {
+ function getSignatureHelpItems(fileName, position, _a) {
+ var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason;
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
- return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken);
+ return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken);
}
/// Syntactic features
function getNonBoundSourceFile(fileName) {
@@ -109859,7 +111050,7 @@ var ts;
return undefined;
}
switch (node.kind) {
- case 185 /* PropertyAccessExpression */:
+ case 187 /* PropertyAccessExpression */:
case 146 /* QualifiedName */:
case 9 /* StringLiteral */:
case 86 /* FalseKeyword */:
@@ -109867,7 +111058,7 @@ var ts;
case 95 /* NullKeyword */:
case 97 /* SuperKeyword */:
case 99 /* ThisKeyword */:
- case 174 /* ThisType */:
+ case 176 /* ThisType */:
case 71 /* Identifier */:
break;
// Cant create the text span
@@ -109884,7 +111075,7 @@ var ts;
// If this is name of a module declarations, check if this is right side of dotted module name
// If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of
// Then this name is name from dotted module
- if (nodeForStartPos.parent.parent.kind === 239 /* ModuleDeclaration */ &&
+ if (nodeForStartPos.parent.parent.kind === 242 /* ModuleDeclaration */ &&
nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
// Use parent module declarations name for start pos
nodeForStartPos = nodeForStartPos.parent.parent.name;
@@ -109954,7 +111145,7 @@ var ts;
braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); });
function getBraceMatchingAtPosition(fileName, position) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false);
+ var token = ts.getTouchingToken(sourceFile, position);
var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined;
var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile);
// We want to order the braces when we return the result.
@@ -109995,7 +111186,7 @@ var ts;
return [];
}
function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) {
- if (preferences === void 0) { preferences = ts.defaultPreferences; }
+ if (preferences === void 0) { preferences = ts.emptyOptions; }
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
var span = ts.createTextSpanFromBounds(start, end);
@@ -110006,7 +111197,7 @@ var ts;
});
}
function getCombinedCodeFix(scope, fixId, formatOptions, preferences) {
- if (preferences === void 0) { preferences = ts.defaultPreferences; }
+ if (preferences === void 0) { preferences = ts.emptyOptions; }
synchronizeHostData();
ts.Debug.assert(scope.type === "file");
var sourceFile = getValidSourceFile(scope.fileName);
@@ -110014,7 +111205,7 @@ var ts;
return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences });
}
function organizeImports(scope, formatOptions, preferences) {
- if (preferences === void 0) { preferences = ts.defaultPreferences; }
+ if (preferences === void 0) { preferences = ts.emptyOptions; }
synchronizeHostData();
ts.Debug.assert(scope.type === "file");
var sourceFile = getValidSourceFile(scope.fileName);
@@ -110022,7 +111213,7 @@ var ts;
return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences);
}
function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) {
- if (preferences === void 0) { preferences = ts.defaultPreferences; }
+ if (preferences === void 0) { preferences = ts.emptyOptions; }
return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences);
}
function applyCodeActionCommand(fileName, actionOrUndefined) {
@@ -110085,8 +111276,8 @@ var ts;
}
function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine);
- return range && ts.createTextSpanFromRange(range);
+ var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position);
+ return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined;
}
function getTodoComments(fileName, descriptors) {
// Note: while getting todo comments seems like a syntactic operation, we actually
@@ -110214,8 +111405,7 @@ var ts;
}
function getRenameInfo(fileName, position) {
synchronizeHostData();
- var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings());
- return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position);
+ return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position);
}
function getRefactorContext(file, positionOrRange, preferences, formatOptions) {
var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1];
@@ -110231,13 +111421,13 @@ var ts;
};
}
function getApplicableRefactors(fileName, positionOrRange, preferences) {
- if (preferences === void 0) { preferences = ts.defaultPreferences; }
+ if (preferences === void 0) { preferences = ts.emptyOptions; }
synchronizeHostData();
var file = getValidSourceFile(fileName);
return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences));
}
function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) {
- if (preferences === void 0) { preferences = ts.defaultPreferences; }
+ if (preferences === void 0) { preferences = ts.emptyOptions; }
synchronizeHostData();
var file = getValidSourceFile(fileName);
return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName);
@@ -110331,7 +111521,7 @@ var ts;
*/
function literalIsName(node) {
return ts.isDeclarationName(node) ||
- node.parent.kind === 254 /* ExternalModuleReference */ ||
+ node.parent.kind === 257 /* ExternalModuleReference */ ||
isArgumentOfElementAccessExpression(node) ||
ts.isLiteralComputedPropertyDeclarationName(node);
}
@@ -110349,7 +111539,7 @@ var ts;
// falls through
case 71 /* Identifier */:
return ts.isObjectLiteralElement(node.parent) &&
- (node.parent.parent.kind === 184 /* ObjectLiteralExpression */ || node.parent.parent.kind === 263 /* JsxAttributes */) &&
+ (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) &&
node.parent.name === node ? node.parent : undefined;
}
return undefined;
@@ -110388,7 +111578,7 @@ var ts;
function isArgumentOfElementAccessExpression(node) {
return node &&
node.parent &&
- node.parent.kind === 186 /* ElementAccessExpression */ &&
+ node.parent.kind === 188 /* ElementAccessExpression */ &&
node.parent.argumentExpression === node;
}
/**
@@ -110419,7 +111609,7 @@ var ts;
if (sourceFile.isDeclarationFile) {
return undefined;
}
- var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
+ var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position);
var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line
@@ -110468,114 +111658,114 @@ var ts;
if (node) {
var parent = node.parent;
switch (node.kind) {
- case 214 /* VariableStatement */:
+ case 217 /* VariableStatement */:
// Span on first variable declaration
return spanInVariableDeclaration(node.declarationList.declarations[0]);
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
case 152 /* PropertyDeclaration */:
case 151 /* PropertySignature */:
return spanInVariableDeclaration(node);
case 149 /* Parameter */:
return spanInParameterDeclaration(node);
- case 234 /* FunctionDeclaration */:
+ case 237 /* FunctionDeclaration */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
case 156 /* GetAccessor */:
case 157 /* SetAccessor */:
case 155 /* Constructor */:
- case 192 /* FunctionExpression */:
- case 193 /* ArrowFunction */:
+ case 194 /* FunctionExpression */:
+ case 195 /* ArrowFunction */:
return spanInFunctionDeclaration(node);
- case 213 /* Block */:
+ case 216 /* Block */:
if (ts.isFunctionBlock(node)) {
return spanInFunctionBlock(node);
}
// falls through
- case 240 /* ModuleBlock */:
+ case 243 /* ModuleBlock */:
return spanInBlock(node);
- case 269 /* CatchClause */:
+ case 272 /* CatchClause */:
return spanInBlock(node.block);
- case 216 /* ExpressionStatement */:
+ case 219 /* ExpressionStatement */:
// span on the expression
return textSpan(node.expression);
- case 225 /* ReturnStatement */:
+ case 228 /* ReturnStatement */:
// span on return keyword and expression if present
return textSpan(node.getChildAt(0), node.expression);
- case 219 /* WhileStatement */:
+ case 222 /* WhileStatement */:
// Span on while(...)
return textSpanEndingAtNextToken(node, node.expression);
- case 218 /* DoStatement */:
+ case 221 /* DoStatement */:
// span in statement of the do statement
return spanInNode(node.statement);
- case 231 /* DebuggerStatement */:
+ case 234 /* DebuggerStatement */:
// span on debugger keyword
return textSpan(node.getChildAt(0));
- case 217 /* IfStatement */:
+ case 220 /* IfStatement */:
// set on if(..) span
return textSpanEndingAtNextToken(node, node.expression);
- case 228 /* LabeledStatement */:
+ case 231 /* LabeledStatement */:
// span in statement
return spanInNode(node.statement);
- case 224 /* BreakStatement */:
- case 223 /* ContinueStatement */:
+ case 227 /* BreakStatement */:
+ case 226 /* ContinueStatement */:
// On break or continue keyword and label if present
return textSpan(node.getChildAt(0), node.label);
- case 220 /* ForStatement */:
+ case 223 /* ForStatement */:
return spanInForStatement(node);
- case 221 /* ForInStatement */:
+ case 224 /* ForInStatement */:
// span of for (a in ...)
return textSpanEndingAtNextToken(node, node.expression);
- case 222 /* ForOfStatement */:
+ case 225 /* ForOfStatement */:
// span in initializer
return spanInInitializerOfForLike(node);
- case 227 /* SwitchStatement */:
+ case 230 /* SwitchStatement */:
// span on switch(...)
return textSpanEndingAtNextToken(node, node.expression);
- case 266 /* CaseClause */:
- case 267 /* DefaultClause */:
+ case 269 /* CaseClause */:
+ case 270 /* DefaultClause */:
// span in first statement of the clause
return spanInNode(node.statements[0]);
- case 230 /* TryStatement */:
+ case 233 /* TryStatement */:
// span in try block
return spanInBlock(node.tryBlock);
- case 229 /* ThrowStatement */:
+ case 232 /* ThrowStatement */:
// span in throw ...
return textSpan(node, node.expression);
- case 249 /* ExportAssignment */:
+ case 252 /* ExportAssignment */:
// span on export = id
return textSpan(node, node.expression);
- case 243 /* ImportEqualsDeclaration */:
+ case 246 /* ImportEqualsDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleReference);
- case 244 /* ImportDeclaration */:
+ case 247 /* ImportDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleSpecifier);
- case 250 /* ExportDeclaration */:
+ case 253 /* ExportDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleSpecifier);
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
// span on complete module if it is instantiated
if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
return undefined;
}
// falls through
- case 235 /* ClassDeclaration */:
- case 238 /* EnumDeclaration */:
- case 273 /* EnumMember */:
- case 182 /* BindingElement */:
+ case 238 /* ClassDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 276 /* EnumMember */:
+ case 184 /* BindingElement */:
// span on complete node
return textSpan(node);
- case 226 /* WithStatement */:
+ case 229 /* WithStatement */:
// span in statement
return spanInNode(node.statement);
case 150 /* Decorator */:
return spanInNodeArray(parent.decorators);
- case 180 /* ObjectBindingPattern */:
- case 181 /* ArrayBindingPattern */:
+ case 182 /* ObjectBindingPattern */:
+ case 183 /* ArrayBindingPattern */:
return spanInBindingPattern(node);
// No breakpoint in interface, type alias
- case 236 /* InterfaceDeclaration */:
- case 237 /* TypeAliasDeclaration */:
+ case 239 /* InterfaceDeclaration */:
+ case 240 /* TypeAliasDeclaration */:
return undefined;
// Tokens:
case 25 /* SemicolonToken */:
@@ -110618,13 +111808,13 @@ var ts;
// `a` or `...c` or `d: x` from
// `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern
if ((node.kind === 71 /* Identifier */ ||
- node.kind === 204 /* SpreadElement */ ||
- node.kind === 270 /* PropertyAssignment */ ||
- node.kind === 271 /* ShorthandPropertyAssignment */) &&
+ node.kind === 206 /* SpreadElement */ ||
+ node.kind === 273 /* PropertyAssignment */ ||
+ node.kind === 274 /* ShorthandPropertyAssignment */) &&
ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) {
return textSpan(node);
}
- if (node.kind === 200 /* BinaryExpression */) {
+ if (node.kind === 202 /* BinaryExpression */) {
var _a = node, left = _a.left, operatorToken = _a.operatorToken;
// Set breakpoint in destructuring pattern if its destructuring assignment
// [a, b, c] or {a, b, c} of
@@ -110646,22 +111836,22 @@ var ts;
}
if (ts.isExpressionNode(node)) {
switch (parent.kind) {
- case 218 /* DoStatement */:
+ case 221 /* DoStatement */:
// Set span as if on while keyword
return spanInPreviousNode(node);
case 150 /* Decorator */:
// Set breakpoint on the decorator emit
return spanInNode(node.parent);
- case 220 /* ForStatement */:
- case 222 /* ForOfStatement */:
+ case 223 /* ForStatement */:
+ case 225 /* ForOfStatement */:
return textSpan(node);
- case 200 /* BinaryExpression */:
+ case 202 /* BinaryExpression */:
if (node.parent.operatorToken.kind === 26 /* CommaToken */) {
// If this is a comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
break;
- case 193 /* ArrowFunction */:
+ case 195 /* ArrowFunction */:
if (node.parent.body === node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
@@ -110670,20 +111860,20 @@ var ts;
}
}
switch (node.parent.kind) {
- case 270 /* PropertyAssignment */:
+ case 273 /* PropertyAssignment */:
// If this is name of property assignment, set breakpoint in the initializer
if (node.parent.name === node &&
!ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
return spanInNode(node.parent.initializer);
}
break;
- case 190 /* TypeAssertionExpression */:
+ case 192 /* TypeAssertionExpression */:
// Breakpoint in type assertion goes to its operand
if (node.parent.type === node) {
return spanInNextNode(node.parent.type);
}
break;
- case 232 /* VariableDeclaration */:
+ case 235 /* VariableDeclaration */:
case 149 /* Parameter */: {
// initializer of variable/parameter declaration go to previous node
var _b = node.parent, initializer = _b.initializer, type = _b.type;
@@ -110692,7 +111882,7 @@ var ts;
}
break;
}
- case 200 /* BinaryExpression */: {
+ case 202 /* BinaryExpression */: {
var left = node.parent.left;
if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
// If initializer of destructuring assignment move to previous token
@@ -110722,7 +111912,7 @@ var ts;
}
function spanInVariableDeclaration(variableDeclaration) {
// If declaration of for in statement, just set the span in parent
- if (variableDeclaration.parent.parent.kind === 221 /* ForInStatement */) {
+ if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) {
return spanInNode(variableDeclaration.parent.parent);
}
var parent = variableDeclaration.parent;
@@ -110734,7 +111924,7 @@ var ts;
// or its declaration from 'for of'
if (variableDeclaration.initializer ||
ts.hasModifier(variableDeclaration, 1 /* Export */) ||
- parent.parent.kind === 222 /* ForOfStatement */) {
+ parent.parent.kind === 225 /* ForOfStatement */) {
return textSpanFromVariableDeclaration(variableDeclaration);
}
if (ts.isVariableDeclarationList(variableDeclaration.parent) &&
@@ -110775,7 +111965,7 @@ var ts;
}
function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
return ts.hasModifier(functionDeclaration, 1 /* Export */) ||
- (functionDeclaration.parent.kind === 235 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */);
+ (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */);
}
function spanInFunctionDeclaration(functionDeclaration) {
// No breakpoints in the function signature
@@ -110798,26 +111988,26 @@ var ts;
}
function spanInBlock(block) {
switch (block.parent.kind) {
- case 239 /* ModuleDeclaration */:
+ case 242 /* ModuleDeclaration */:
if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
return undefined;
}
// falls through
// Set on parent if on same line otherwise on first statement
- case 219 /* WhileStatement */:
- case 217 /* IfStatement */:
- case 221 /* ForInStatement */:
+ case 222 /* WhileStatement */:
+ case 220 /* IfStatement */:
+ case 224 /* ForInStatement */:
return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
// Set span on previous token if it starts on same line otherwise on the first statement of the block
- case 220 /* ForStatement */:
- case 222 /* ForOfStatement */:
+ case 223 /* ForStatement */:
+ case 225 /* ForOfStatement */:
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
}
// Default action is to set on first statement
return spanInNode(block.statements[0]);
}
function spanInInitializerOfForLike(forLikeStatement) {
- if (forLikeStatement.initializer.kind === 233 /* VariableDeclarationList */) {
+ if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) {
// Declaration list - set breakpoint in first declaration
var variableDeclarationList = forLikeStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
@@ -110842,21 +112032,21 @@ var ts;
}
function spanInBindingPattern(bindingPattern) {
// Set breakpoint in first binding element
- var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 206 /* OmittedExpression */ ? element : undefined; });
+ var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; });
if (firstBindingElement) {
return spanInNode(firstBindingElement);
}
// Empty binding pattern of binding element, set breakpoint on binding element
- if (bindingPattern.parent.kind === 182 /* BindingElement */) {
+ if (bindingPattern.parent.kind === 184 /* BindingElement */) {
return textSpan(bindingPattern.parent);
}
// Variable declaration is used as the span
return textSpanFromVariableDeclaration(bindingPattern.parent);
}
function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) {
- ts.Debug.assert(node.kind !== 181 /* ArrayBindingPattern */ && node.kind !== 180 /* ObjectBindingPattern */);
- var elements = node.kind === 183 /* ArrayLiteralExpression */ ? node.elements : node.properties;
- var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 206 /* OmittedExpression */ ? element : undefined; });
+ ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */);
+ var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties;
+ var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; });
if (firstBindingElement) {
return spanInNode(firstBindingElement);
}
@@ -110864,18 +112054,18 @@ var ts;
// just nested element in another destructuring assignment
// set breakpoint on assignment when parent is destructuring assignment
// Otherwise set breakpoint for this element
- return textSpan(node.parent.kind === 200 /* BinaryExpression */ ? node.parent : node);
+ return textSpan(node.parent.kind === 202 /* BinaryExpression */ ? node.parent : node);
}
// Tokens:
function spanInOpenBraceToken(node) {
switch (node.parent.kind) {
- case 238 /* EnumDeclaration */:
+ case 241 /* EnumDeclaration */:
var enumDeclaration = node.parent;
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
- case 235 /* ClassDeclaration */:
+ case 238 /* ClassDeclaration */:
var classDeclaration = node.parent;
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
- case 241 /* CaseBlock */:
+ case 244 /* CaseBlock */:
return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]);
}
// Default to parent node
@@ -110883,25 +112073,25 @@ var ts;
}
function spanInCloseBraceToken(node) {
switch (node.parent.kind) {
- case 240 /* ModuleBlock */:
+ case 243 /* ModuleBlock */:
// If this is not an instantiated module block, no bp span
if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) {
return undefined;
}
// falls through
- case 238 /* EnumDeclaration */:
- case 235 /* ClassDeclaration */:
+ case 241 /* EnumDeclaration */:
+ case 238 /* ClassDeclaration */:
// Span on close brace token
return textSpan(node);
- case 213 /* Block */:
+ case 216 /* Block */:
if (ts.isFunctionBlock(node.parent)) {
// Span on close brace token
return textSpan(node);
}
// falls through
- case 269 /* CatchClause */:
+ case 272 /* CatchClause */:
return spanInNode(ts.lastOrUndefined(node.parent.statements));
- case 241 /* CaseBlock */:
+ case 244 /* CaseBlock */:
// breakpoint in last statement of the last clause
var caseBlock = node.parent;
var lastClause = ts.lastOrUndefined(caseBlock.clauses);
@@ -110909,7 +112099,7 @@ var ts;
return spanInNode(ts.lastOrUndefined(lastClause.statements));
}
return undefined;
- case 180 /* ObjectBindingPattern */:
+ case 182 /* ObjectBindingPattern */:
// Breakpoint in last binding element or binding pattern if it contains no elements
var bindingPattern = node.parent;
return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
@@ -110925,7 +112115,7 @@ var ts;
}
function spanInCloseBracketToken(node) {
switch (node.parent.kind) {
- case 181 /* ArrayBindingPattern */:
+ case 183 /* ArrayBindingPattern */:
// Breakpoint in last binding element or binding pattern if it contains no elements
var bindingPattern = node.parent;
return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
@@ -110940,12 +112130,12 @@ var ts;
}
}
function spanInOpenParenToken(node) {
- if (node.parent.kind === 218 /* DoStatement */ || // Go to while keyword and do action instead
- node.parent.kind === 187 /* CallExpression */ ||
- node.parent.kind === 188 /* NewExpression */) {
+ if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead
+ node.parent.kind === 189 /* CallExpression */ ||
+ node.parent.kind === 190 /* NewExpression */) {
return spanInPreviousNode(node);
}
- if (node.parent.kind === 191 /* ParenthesizedExpression */) {
+ if (node.parent.kind === 193 /* ParenthesizedExpression */) {
return spanInNextNode(node);
}
// Default to parent node
@@ -110954,21 +112144,21 @@ var ts;
function spanInCloseParenToken(node) {
// Is this close paren token of parameter list, set span in previous token
switch (node.parent.kind) {
- case 192 /* FunctionExpression */:
- case 234 /* FunctionDeclaration */:
- case 193 /* ArrowFunction */:
+ case 194 /* FunctionExpression */:
+ case 237 /* FunctionDeclaration */:
+ case 195 /* ArrowFunction */:
case 154 /* MethodDeclaration */:
case 153 /* MethodSignature */:
case 156 /* GetAccessor */:
case 157 /* SetAccessor */:
case 155 /* Constructor */:
- case 219 /* WhileStatement */:
- case 218 /* DoStatement */:
- case 220 /* ForStatement */:
- case 222 /* ForOfStatement */:
- case 187 /* CallExpression */:
- case 188 /* NewExpression */:
- case 191 /* ParenthesizedExpression */:
+ case 222 /* WhileStatement */:
+ case 221 /* DoStatement */:
+ case 223 /* ForStatement */:
+ case 225 /* ForOfStatement */:
+ case 189 /* CallExpression */:
+ case 190 /* NewExpression */:
+ case 193 /* ParenthesizedExpression */:
return spanInPreviousNode(node);
// Default to parent node
default:
@@ -110978,20 +112168,20 @@ var ts;
function spanInColonToken(node) {
// Is this : specifying return annotation of the function declaration
if (ts.isFunctionLike(node.parent) ||
- node.parent.kind === 270 /* PropertyAssignment */ ||
+ node.parent.kind === 273 /* PropertyAssignment */ ||
node.parent.kind === 149 /* Parameter */) {
return spanInPreviousNode(node);
}
return spanInNode(node.parent);
}
function spanInGreaterThanOrLessThanToken(node) {
- if (node.parent.kind === 190 /* TypeAssertionExpression */) {
+ if (node.parent.kind === 192 /* TypeAssertionExpression */) {
return spanInNextNode(node);
}
return spanInNode(node.parent);
}
function spanInWhileKeyword(node) {
- if (node.parent.kind === 218 /* DoStatement */) {
+ if (node.parent.kind === 221 /* DoStatement */) {
// Set span on while expression
return textSpanEndingAtNextToken(node, node.parent.expression);
}
@@ -110999,7 +112189,7 @@ var ts;
return spanInNode(node.parent);
}
function spanInOfKeyword(node) {
- if (node.parent.kind === 222 /* ForOfStatement */) {
+ if (node.parent.kind === 225 /* ForOfStatement */) {
// Set using next token
return spanInNextNode(node);
}
@@ -111419,9 +112609,9 @@ var ts;
return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); });
};
/// SIGNATUREHELP
- LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) {
+ LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) {
var _this = this;
- return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); });
+ return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); });
};
/// GOTO DEFINITION
/**
@@ -112219,18 +113409,24 @@ var ts;
})(ts || (ts = {}));
//# sourceMappingURL=jsTyping.js.map
"use strict";
-var __assign = (this && this.__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;
+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 = 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]; };
+ 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; }
@@ -112465,6 +113661,7 @@ var ts;
CommandTypes["Change"] = "change";
CommandTypes["Close"] = "close";
CommandTypes["Completions"] = "completions";
+ CommandTypes["CompletionInfo"] = "completionInfo";
CommandTypes["CompletionsFull"] = "completions-full";
CommandTypes["CompletionDetails"] = "completionEntryDetails";
CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full";
@@ -112596,16 +113793,15 @@ var ts;
var server;
(function (server) {
var TextStorage = (function () {
- function TextStorage(host, fileName) {
+ function TextStorage(host, fileName, initialVersion) {
this.host = host;
this.fileName = fileName;
- this.svcVersion = 0;
- this.textVersion = 0;
+ this.version = initialVersion || { svc: 0, text: 0 };
}
TextStorage.prototype.getVersion = function () {
return this.svc
- ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshotVersion()
- : "Text-" + this.textVersion;
+ ? "SVC-" + this.version.svc + "-" + this.svc.getSnapshotVersion()
+ : "Text-" + this.version.text;
};
TextStorage.prototype.hasScriptVersionCache_TestOnly = function () {
return this.svc !== undefined;
@@ -112617,7 +113813,7 @@ var ts;
this.svc = undefined;
this.text = newText;
this.lineMap = undefined;
- this.textVersion++;
+ this.version.text++;
};
TextStorage.prototype.edit = function (start, end, newText) {
this.switchToScriptVersionCache().edit(start, end - start, newText);
@@ -112684,7 +113880,7 @@ var ts;
TextStorage.prototype.switchToScriptVersionCache = function () {
if (!this.svc || this.pendingReloadFromDisk) {
this.svc = server.ScriptVersionCache.fromString(this.getOrLoadText());
- this.svcVersion++;
+ this.version.svc++;
}
return this.svc;
};
@@ -112716,7 +113912,7 @@ var ts;
}
server.isDynamicFileName = isDynamicFileName;
var ScriptInfo = (function () {
- function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path) {
+ function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path, initialVersion) {
this.host = host;
this.fileName = fileName;
this.scriptKind = scriptKind;
@@ -112724,7 +113920,7 @@ var ts;
this.path = path;
this.containingProjects = [];
this.isDynamic = isDynamicFileName(fileName);
- this.textStorage = new TextStorage(host, fileName);
+ this.textStorage = new TextStorage(host, fileName, initialVersion);
if (hasMixedContent || this.isDynamic) {
this.textStorage.reload("");
this.realpath = this.path;
@@ -112733,6 +113929,9 @@ var ts;
? scriptKind
: ts.getScriptKindFromFileName(fileName);
}
+ ScriptInfo.prototype.getVersion = function () {
+ return this.textStorage.version;
+ };
ScriptInfo.prototype.isDynamicOrHasMixedContent = function () {
return this.hasMixedContent || this.isDynamic;
};
@@ -112880,7 +114079,7 @@ var ts;
}
if (preferences) {
if (!this.preferences) {
- this.preferences = ts.defaultPreferences;
+ this.preferences = ts.emptyOptions;
}
this.preferences = __assign({}, this.preferences, preferences);
}
@@ -114275,6 +115474,7 @@ var ts;
function ProjectService(opts) {
var _this = this;
this.filenameToScriptInfo = ts.createMap();
+ this.filenameToScriptInfoVersion = ts.createMap();
this.allJsFilesForOpenFileTelemetry = ts.createMap();
this.externalProjectToConfiguredProjectMap = ts.createMap();
this.externalProjects = [];
@@ -114323,7 +115523,7 @@ var ts;
this.typingsCache = new server.TypingsCache(this.typingsInstaller);
this.hostConfiguration = {
formatCodeOptions: server.getDefaultFormatCodeSettings(this.host),
- preferences: ts.defaultPreferences,
+ preferences: ts.emptyOptions,
hostInfo: "Unknown host",
extraFileExtensions: []
};
@@ -114494,18 +115694,29 @@ var ts;
}
return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName));
};
- ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) {
- var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
- if (ensureProject && (!scriptInfo || scriptInfo.isOrphan())) {
- this.ensureProjectStructuresUptoDate();
- scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
- if (!scriptInfo) {
- return server.Errors.ThrowNoProject();
- }
- return scriptInfo.getDefaultProject();
+ ProjectService.prototype.forEachProject = function (cb) {
+ for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
+ var p = _a[_i];
+ cb(p);
}
+ this.configuredProjects.forEach(cb);
+ this.externalProjects.forEach(cb);
+ };
+ ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) {
+ return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName);
+ };
+ ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) {
+ var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined;
};
+ ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) {
+ return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName);
+ };
+ ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) {
+ this.ensureProjectStructuresUptoDate();
+ var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
+ return scriptInfo ? scriptInfo.getDefaultProject() : server.Errors.ThrowNoProject();
+ };
ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) {
this.ensureProjectStructuresUptoDate();
return this.getScriptInfo(uncheckedFileName);
@@ -114531,6 +115742,12 @@ var ts;
var info = this.getScriptInfoForNormalizedPath(file);
return info && info.getPreferences() || this.hostConfiguration.preferences;
};
+ ProjectService.prototype.getHostFormatCodeOptions = function () {
+ return this.hostConfiguration.formatCodeOptions;
+ };
+ ProjectService.prototype.getHostPreferences = function () {
+ return this.hostConfiguration.preferences;
+ };
ProjectService.prototype.onSourceFileChanged = function (fileName, eventKind, path) {
var info = this.getScriptInfoForPath(path);
if (!info) {
@@ -114690,6 +115907,7 @@ var ts;
};
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);
@@ -115282,8 +116500,9 @@ var ts;
if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) {
return;
}
- info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path);
+ info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path));
this.filenameToScriptInfo.set(info.path, info);
+ this.filenameToScriptInfoVersion.delete(info.path);
if (!openedByClient) {
this.watchClosedScriptInfo(info);
}
@@ -115853,7 +117072,9 @@ var ts;
function formatRelatedInformation(info) {
if (!info.file) {
return {
- message: ts.flattenDiagnosticMessageText(info.messageText, "\n")
+ message: ts.flattenDiagnosticMessageText(info.messageText, "\n"),
+ category: ts.diagnosticCategoryName(info),
+ code: info.code
};
}
return {
@@ -115862,7 +117083,9 @@ var ts;
end: convertToLocation(ts.getLineAndCharacterOfPosition(info.file, info.start + info.length)),
file: info.file.fileName
},
- message: ts.flattenDiagnosticMessageText(info.messageText, "\n")
+ message: ts.flattenDiagnosticMessageText(info.messageText, "\n"),
+ category: ts.diagnosticCategoryName(info),
+ code: info.code
};
}
function convertToLocation(lineAndCharacter) {
@@ -115888,13 +117111,7 @@ var ts;
? __assign({}, common, { fileName: diag.file && diag.file.fileName }) : common;
}
function allEditsBeforePos(edits, pos) {
- for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
- var edit = edits_1[_i];
- if (ts.textSpanEnd(edit.span) >= pos) {
- return false;
- }
- }
- return true;
+ return edits.every(function (edit) { return ts.textSpanEnd(edit.span) < pos; });
}
server.CommandNames = server.protocol.CommandTypes;
function formatMessage(msg, logger, byteLength, newLine) {
@@ -116140,11 +117357,14 @@ var ts;
_a[server.CommandNames.FormatRangeFull] = function (request) {
return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments));
},
+ _a[server.CommandNames.CompletionInfo] = function (request) {
+ return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionInfo));
+ },
_a[server.CommandNames.Completions] = function (request) {
- return _this.requiredResponse(_this.getCompletions(request.arguments, true));
+ return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.Completions));
},
_a[server.CommandNames.CompletionsFull] = function (request) {
- return _this.requiredResponse(_this.getCompletions(request.arguments, false));
+ return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull));
},
_a[server.CommandNames.CompletionDetails] = function (request) {
return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, true));
@@ -116940,7 +118160,7 @@ var ts;
};
Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) {
var file = server.toNormalizedPath(args.file);
- var project = this.getProject(args.projectFileName) || this.projectService.getDefaultProjectForFile(file, false);
+ var project = this.getProject(args.projectFileName) || this.projectService.tryGetDefaultProjectForFile(file);
if (!project) {
return server.Errors.ThrowNoProject();
}
@@ -116951,7 +118171,7 @@ var ts;
};
Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) {
var file = server.toNormalizedPath(uncheckedFileName);
- var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, true);
+ var project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file);
return { file: file, project: project };
};
Session.prototype.getOutliningSpans = function (args, simplifiedResult) {
@@ -117103,25 +118323,28 @@ var ts;
};
});
};
- Session.prototype.getCompletions = function (args, simplifiedResult) {
+ Session.prototype.getCompletions = function (args, kind) {
var _this = this;
- var prefix = args.prefix || "";
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
var position = this.getPosition(args, scriptInfo);
var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions }));
- if (simplifiedResult) {
- return ts.mapDefined(completions && completions.entries, function (entry) {
- if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
- var name = entry.name, kind = 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;
- return { name: name, kind: kind, 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); });
- }
- else {
+ if (completions === undefined)
+ return undefined;
+ if (kind === "completions-full")
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;
+ 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")
+ return entries;
+ var res = __assign({}, completions, { entries: entries });
+ return res;
};
Session.prototype.getCompletionEntryDetails = function (args, simplifiedResult) {
var _this = this;
@@ -117173,7 +118396,7 @@ var ts;
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
var position = this.getPosition(args, scriptInfo);
- var helpItems = project.getLanguageService().getSignatureHelpItems(file, position);
+ var helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args);
if (!helpItems) {
return undefined;
}
@@ -117198,7 +118421,7 @@ var ts;
var _this = this;
return ts.mapDefined(fileNames, function (uncheckedFileName) {
var fileName = server.toNormalizedPath(uncheckedFileName);
- var project = defaultProject || _this.projectService.getDefaultProjectForFile(fileName, false);
+ var project = defaultProject || _this.projectService.tryGetDefaultProjectForFile(fileName);
return project && { fileName: fileName, project: project };
});
};
@@ -117311,6 +118534,8 @@ var ts;
var bakedItem = {
name: navItem.name,
kind: navItem.kind,
+ isCaseSensitive: navItem.isCaseSensitive,
+ matchKind: navItem.matchKind,
file: navItem.fileName,
start: scriptInfo.positionToLineOffset(navItem.textSpan.start),
end: scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan))
@@ -117318,9 +118543,6 @@ var ts;
if (navItem.kindModifiers && (navItem.kindModifiers !== "")) {
bakedItem.kindModifiers = navItem.kindModifiers;
}
- if (navItem.matchKind !== "none") {
- bakedItem.matchKind = navItem.matchKind;
- }
if (navItem.containerName && (navItem.containerName.length > 0)) {
bakedItem.containerName = navItem.containerName;
}
@@ -117429,9 +118651,26 @@ var ts;
}
};
Session.prototype.getEditsForFileRename = function (args, simplifiedResult) {
- var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
- var changes = project.getLanguageService().getEditsForFileRename(server.toNormalizedPath(args.oldFilePath), server.toNormalizedPath(args.newFilePath), this.getFormatOptions(file), this.getPreferences(file));
- return simplifiedResult ? this.mapTextChangesToCodeEdits(project, changes) : changes;
+ var _this = this;
+ var oldPath = server.toNormalizedPath(args.oldFilePath);
+ var newPath = server.toNormalizedPath(args.newFilePath);
+ var formatOptions = this.getHostFormatOptions();
+ var preferences = this.getHostPreferences();
+ var changes = [];
+ this.projectService.forEachProject(function (project) {
+ if (project.isOrphan() || !project.languageServiceEnabled)
+ return;
+ var _loop_8 = function (fileTextChanges) {
+ if (!changes.some(function (f) { return f.fileName === fileTextChanges.fileName; })) {
+ changes.push(simplifiedResult ? _this.mapTextChangeToCodeEdit(project, fileTextChanges) : fileTextChanges);
+ }
+ };
+ for (var _i = 0, _a = project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); _i < _a.length; _i++) {
+ var fileTextChanges = _a[_i];
+ _loop_8(fileTextChanges);
+ }
+ });
+ return changes;
};
Session.prototype.getCodeFixes = function (args, simplifiedResult) {
var _this = this;
@@ -117493,10 +118732,12 @@ var ts;
};
Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) {
var _this = this;
- return textChanges.map(function (change) {
- var path = server.normalizedPathToPath(server.toNormalizedPath(change.fileName), _this.host.getCurrentDirectory(), function (fileName) { return _this.getCanonicalFileName(fileName); });
- return mapTextChangesToCodeEdits(change, project.getSourceFileOrConfigFile(path));
- });
+ return textChanges.map(function (change) { return _this.mapTextChangeToCodeEdit(project, change); });
+ };
+ Session.prototype.mapTextChangeToCodeEdit = function (project, change) {
+ var _this = this;
+ var path = server.normalizedPathToPath(server.toNormalizedPath(change.fileName), this.host.getCurrentDirectory(), function (fileName) { return _this.getCanonicalFileName(fileName); });
+ return mapTextChangesToCodeEdits(change, project.getSourceFileOrConfigFile(path));
};
Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) {
return {
@@ -117534,7 +118775,7 @@ var ts;
var lowPriorityFiles = [];
var veryLowPriorityFiles = [];
var normalizedFileName = server.toNormalizedPath(fileName);
- var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true);
+ var project = this.projectService.ensureDefaultProjectForFile(normalizedFileName);
for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) {
var fileNameInProject = fileNamesInProject_1[_i];
if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) {
@@ -117650,6 +118891,12 @@ var ts;
Session.prototype.getPreferences = function (file) {
return this.projectService.getPreferences(file);
};
+ Session.prototype.getHostFormatOptions = function () {
+ return this.projectService.getHostFormatCodeOptions();
+ };
+ Session.prototype.getHostPreferences = function () {
+ return this.projectService.getHostPreferences();
+ };
return Session;
}());
server.Session = Session;
@@ -117685,8 +118932,8 @@ var ts;
}
server.getLocationInNewDocument = getLocationInNewDocument;
function applyEdits(text, textFilename, edits) {
- for (var _i = 0, edits_2 = edits; _i < edits_2.length; _i++) {
- var _a = edits_2[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
+ for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
+ var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
if (fileName !== textFilename) {
continue;
}
@@ -118548,7 +119795,7 @@ var ts;
});
Logger.prototype.write = function (s) {
if (this.fd >= 0) {
- var buf = new Buffer(s);
+ var buf = Buffer.from ? Buffer.from(s) : new Buffer(s);
// tslint:disable-next-line no-null-keyword
fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null); // TODO: GH#18217
}
@@ -119145,7 +120392,7 @@ var ts;
sys.watchDirectory = watchDirectorySwallowingException;
}
// Override sys.write because fs.writeSync is not reliable on Node 4
- sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); };
+ sys.write = function (s) { return writeMessage(Buffer.from ? Buffer.from(s, "utf8") : new Buffer(s, "utf8")); };
sys.watchFile = function (fileName, callback) {
var watchedFile = pollingWatchedFileSet.addFile(fileName, callback);
return {
diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts
index 44036c3fe28..ad8fd411384 100644
--- a/lib/tsserverlibrary.d.ts
+++ b/lib/tsserverlibrary.d.ts
@@ -148,7 +148,7 @@ declare namespace ts {
*/
function flatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[];
function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] | undefined;
- function flatMapIterator(iter: Iterator, mapfn: (x: T) => U[] | Iterator | undefined): Iterator;
+ function flatMapIterator(iter: Iterator, mapfn: (x: T) => ReadonlyArray | Iterator | undefined): Iterator;
/**
* Maps an array. If the mapped value is an array, it is spread into the result.
* Avoids allocation if all elements map to themselves.
@@ -241,7 +241,6 @@ declare namespace ts {
* Returns a new sorted array.
*/
function sort(array: ReadonlyArray, comparer: Comparer): T[];
- function best(iter: Iterator, isBetter: (a: T, b: T) => boolean): T | undefined;
function arrayIterator(array: ReadonlyArray): Iterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
@@ -364,6 +363,7 @@ declare namespace ts {
*/
function isString(text: any): text is string;
function tryCast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined;
+ function tryCast(value: T, test: (value: T) => boolean): T | undefined;
function cast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut;
/** Does nothing. */
function noop(_?: {} | null | undefined): void;
@@ -531,7 +531,7 @@ declare namespace ts {
function findBestPatternMatch(values: ReadonlyArray, getPattern: (value: T) => Pattern, candidate: string): T | undefined;
function startsWith(str: string, prefix: string): boolean;
function removePrefix(str: string, prefix: string): string;
- function tryRemovePrefix(str: string, prefix: string): string | undefined;
+ function tryRemovePrefix(str: string, prefix: string, getCanonicalFileName?: GetCanonicalFileName): string | undefined;
function and(f: (arg: T) => boolean, g: (arg: T) => boolean): (arg: T) => boolean;
function or(f: (arg: T) => boolean, g: (arg: T) => boolean): (arg: T) => boolean;
function assertTypeIsNever(_: never): void;
@@ -763,144 +763,147 @@ declare namespace ts {
TypeLiteral = 166,
ArrayType = 167,
TupleType = 168,
- UnionType = 169,
- IntersectionType = 170,
- ConditionalType = 171,
- InferType = 172,
- ParenthesizedType = 173,
- ThisType = 174,
- TypeOperator = 175,
- IndexedAccessType = 176,
- MappedType = 177,
- LiteralType = 178,
- ImportType = 179,
- ObjectBindingPattern = 180,
- ArrayBindingPattern = 181,
- BindingElement = 182,
- ArrayLiteralExpression = 183,
- ObjectLiteralExpression = 184,
- PropertyAccessExpression = 185,
- ElementAccessExpression = 186,
- CallExpression = 187,
- NewExpression = 188,
- TaggedTemplateExpression = 189,
- TypeAssertionExpression = 190,
- ParenthesizedExpression = 191,
- FunctionExpression = 192,
- ArrowFunction = 193,
- DeleteExpression = 194,
- TypeOfExpression = 195,
- VoidExpression = 196,
- AwaitExpression = 197,
- PrefixUnaryExpression = 198,
- PostfixUnaryExpression = 199,
- BinaryExpression = 200,
- ConditionalExpression = 201,
- TemplateExpression = 202,
- YieldExpression = 203,
- SpreadElement = 204,
- ClassExpression = 205,
- OmittedExpression = 206,
- ExpressionWithTypeArguments = 207,
- AsExpression = 208,
- NonNullExpression = 209,
- MetaProperty = 210,
- TemplateSpan = 211,
- SemicolonClassElement = 212,
- Block = 213,
- VariableStatement = 214,
- EmptyStatement = 215,
- ExpressionStatement = 216,
- IfStatement = 217,
- DoStatement = 218,
- WhileStatement = 219,
- ForStatement = 220,
- ForInStatement = 221,
- ForOfStatement = 222,
- ContinueStatement = 223,
- BreakStatement = 224,
- ReturnStatement = 225,
- WithStatement = 226,
- SwitchStatement = 227,
- LabeledStatement = 228,
- ThrowStatement = 229,
- TryStatement = 230,
- DebuggerStatement = 231,
- VariableDeclaration = 232,
- VariableDeclarationList = 233,
- FunctionDeclaration = 234,
- ClassDeclaration = 235,
- InterfaceDeclaration = 236,
- TypeAliasDeclaration = 237,
- EnumDeclaration = 238,
- ModuleDeclaration = 239,
- ModuleBlock = 240,
- CaseBlock = 241,
- NamespaceExportDeclaration = 242,
- ImportEqualsDeclaration = 243,
- ImportDeclaration = 244,
- ImportClause = 245,
- NamespaceImport = 246,
- NamedImports = 247,
- ImportSpecifier = 248,
- ExportAssignment = 249,
- ExportDeclaration = 250,
- NamedExports = 251,
- ExportSpecifier = 252,
- MissingDeclaration = 253,
- ExternalModuleReference = 254,
- JsxElement = 255,
- JsxSelfClosingElement = 256,
- JsxOpeningElement = 257,
- JsxClosingElement = 258,
- JsxFragment = 259,
- JsxOpeningFragment = 260,
- JsxClosingFragment = 261,
- JsxAttribute = 262,
- JsxAttributes = 263,
- JsxSpreadAttribute = 264,
- JsxExpression = 265,
- CaseClause = 266,
- DefaultClause = 267,
- HeritageClause = 268,
- CatchClause = 269,
- PropertyAssignment = 270,
- ShorthandPropertyAssignment = 271,
- SpreadAssignment = 272,
- EnumMember = 273,
- SourceFile = 274,
- Bundle = 275,
- UnparsedSource = 276,
- InputFiles = 277,
- JSDocTypeExpression = 278,
- JSDocAllType = 279,
- JSDocUnknownType = 280,
- JSDocNullableType = 281,
- JSDocNonNullableType = 282,
- JSDocOptionalType = 283,
- JSDocFunctionType = 284,
- JSDocVariadicType = 285,
- JSDocComment = 286,
- JSDocTypeLiteral = 287,
- JSDocSignature = 288,
- JSDocTag = 289,
- JSDocAugmentsTag = 290,
- JSDocClassTag = 291,
- JSDocCallbackTag = 292,
- JSDocParameterTag = 293,
- JSDocReturnTag = 294,
- JSDocThisTag = 295,
- JSDocTypeTag = 296,
- JSDocTemplateTag = 297,
- JSDocTypedefTag = 298,
- JSDocPropertyTag = 299,
- SyntaxList = 300,
- NotEmittedStatement = 301,
- PartiallyEmittedExpression = 302,
- CommaListExpression = 303,
- MergeDeclarationMarker = 304,
- EndOfDeclarationMarker = 305,
- Count = 306,
+ OptionalType = 169,
+ RestType = 170,
+ UnionType = 171,
+ IntersectionType = 172,
+ ConditionalType = 173,
+ InferType = 174,
+ ParenthesizedType = 175,
+ ThisType = 176,
+ TypeOperator = 177,
+ IndexedAccessType = 178,
+ MappedType = 179,
+ LiteralType = 180,
+ ImportType = 181,
+ ObjectBindingPattern = 182,
+ ArrayBindingPattern = 183,
+ BindingElement = 184,
+ ArrayLiteralExpression = 185,
+ ObjectLiteralExpression = 186,
+ PropertyAccessExpression = 187,
+ ElementAccessExpression = 188,
+ CallExpression = 189,
+ NewExpression = 190,
+ TaggedTemplateExpression = 191,
+ TypeAssertionExpression = 192,
+ ParenthesizedExpression = 193,
+ FunctionExpression = 194,
+ ArrowFunction = 195,
+ DeleteExpression = 196,
+ TypeOfExpression = 197,
+ VoidExpression = 198,
+ AwaitExpression = 199,
+ PrefixUnaryExpression = 200,
+ PostfixUnaryExpression = 201,
+ BinaryExpression = 202,
+ ConditionalExpression = 203,
+ TemplateExpression = 204,
+ YieldExpression = 205,
+ SpreadElement = 206,
+ ClassExpression = 207,
+ OmittedExpression = 208,
+ ExpressionWithTypeArguments = 209,
+ AsExpression = 210,
+ NonNullExpression = 211,
+ MetaProperty = 212,
+ SyntheticExpression = 213,
+ TemplateSpan = 214,
+ SemicolonClassElement = 215,
+ Block = 216,
+ VariableStatement = 217,
+ EmptyStatement = 218,
+ ExpressionStatement = 219,
+ IfStatement = 220,
+ DoStatement = 221,
+ WhileStatement = 222,
+ ForStatement = 223,
+ ForInStatement = 224,
+ ForOfStatement = 225,
+ ContinueStatement = 226,
+ BreakStatement = 227,
+ ReturnStatement = 228,
+ WithStatement = 229,
+ SwitchStatement = 230,
+ LabeledStatement = 231,
+ ThrowStatement = 232,
+ TryStatement = 233,
+ DebuggerStatement = 234,
+ VariableDeclaration = 235,
+ VariableDeclarationList = 236,
+ FunctionDeclaration = 237,
+ ClassDeclaration = 238,
+ InterfaceDeclaration = 239,
+ TypeAliasDeclaration = 240,
+ EnumDeclaration = 241,
+ ModuleDeclaration = 242,
+ ModuleBlock = 243,
+ CaseBlock = 244,
+ NamespaceExportDeclaration = 245,
+ ImportEqualsDeclaration = 246,
+ ImportDeclaration = 247,
+ ImportClause = 248,
+ NamespaceImport = 249,
+ NamedImports = 250,
+ ImportSpecifier = 251,
+ ExportAssignment = 252,
+ ExportDeclaration = 253,
+ NamedExports = 254,
+ ExportSpecifier = 255,
+ MissingDeclaration = 256,
+ ExternalModuleReference = 257,
+ JsxElement = 258,
+ JsxSelfClosingElement = 259,
+ JsxOpeningElement = 260,
+ JsxClosingElement = 261,
+ JsxFragment = 262,
+ JsxOpeningFragment = 263,
+ JsxClosingFragment = 264,
+ JsxAttribute = 265,
+ JsxAttributes = 266,
+ JsxSpreadAttribute = 267,
+ JsxExpression = 268,
+ CaseClause = 269,
+ DefaultClause = 270,
+ HeritageClause = 271,
+ CatchClause = 272,
+ PropertyAssignment = 273,
+ ShorthandPropertyAssignment = 274,
+ SpreadAssignment = 275,
+ EnumMember = 276,
+ SourceFile = 277,
+ Bundle = 278,
+ UnparsedSource = 279,
+ InputFiles = 280,
+ JSDocTypeExpression = 281,
+ JSDocAllType = 282,
+ JSDocUnknownType = 283,
+ JSDocNullableType = 284,
+ JSDocNonNullableType = 285,
+ JSDocOptionalType = 286,
+ JSDocFunctionType = 287,
+ JSDocVariadicType = 288,
+ JSDocComment = 289,
+ JSDocTypeLiteral = 290,
+ JSDocSignature = 291,
+ JSDocTag = 292,
+ JSDocAugmentsTag = 293,
+ JSDocClassTag = 294,
+ JSDocCallbackTag = 295,
+ JSDocParameterTag = 296,
+ JSDocReturnTag = 297,
+ JSDocThisTag = 298,
+ JSDocTypeTag = 299,
+ JSDocTemplateTag = 300,
+ JSDocTypedefTag = 301,
+ JSDocPropertyTag = 302,
+ SyntaxList = 303,
+ NotEmittedStatement = 304,
+ PartiallyEmittedExpression = 305,
+ CommaListExpression = 306,
+ MergeDeclarationMarker = 307,
+ EndOfDeclarationMarker = 308,
+ Count = 309,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -912,7 +915,7 @@ declare namespace ts {
FirstFutureReservedWord = 108,
LastFutureReservedWord = 116,
FirstTypeNode = 161,
- LastTypeNode = 179,
+ LastTypeNode = 181,
FirstPunctuation = 17,
LastPunctuation = 70,
FirstToken = 0,
@@ -926,10 +929,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 146,
- FirstJSDocNode = 278,
- LastJSDocNode = 299,
- FirstJSDocTagNode = 289,
- LastJSDocTagNode = 299,
+ FirstJSDocNode = 281,
+ LastJSDocNode = 302,
+ FirstJSDocTagNode = 292,
+ LastJSDocTagNode = 302,
FirstContextualKeyword = 117,
LastContextualKeyword = 145
}
@@ -1352,6 +1355,14 @@ declare namespace ts {
kind: SyntaxKind.TupleType;
elementTypes: NodeArray;
}
+ interface OptionalTypeNode extends TypeNode {
+ kind: SyntaxKind.OptionalType;
+ type: TypeNode;
+ }
+ interface RestTypeNode extends TypeNode {
+ kind: SyntaxKind.RestType;
+ type: TypeNode;
+ }
type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode;
interface UnionTypeNode extends TypeNode {
kind: SyntaxKind.UnionType;
@@ -1482,6 +1493,11 @@ declare namespace ts {
asteriskToken?: AsteriskToken;
expression?: Expression;
}
+ interface SyntheticExpression extends Expression {
+ kind: SyntaxKind.SyntheticExpression;
+ isSpread: boolean;
+ type: Type;
+ }
type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken;
type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken;
type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator;
@@ -1714,7 +1730,10 @@ declare namespace ts {
}
type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute;
- type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression;
+ type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess;
+ interface JsxTagNamePropertyAccess extends PropertyAccessExpression {
+ expression: JsxTagNameExpression;
+ }
interface JsxAttributes extends ObjectLiteralExpressionBase {
parent: JsxOpeningLikeElement;
}
@@ -2541,7 +2560,6 @@ declare namespace ts {
inputSourceFileNames: string[];
sourceMapNames?: string[];
sourceMapMappings: string;
- sourceMapDecodedMappings: SourceMapSpan[];
}
/** Return code used by getEmitOutput function to indicate status of the function */
enum ExitStatus {
@@ -2567,8 +2585,9 @@ declare namespace ts {
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
getPropertyOfType(type: Type, propertyName: string): Symbol | undefined;
+ getTypeOfPropertyOfType(type: Type, propertyName: string): Type | undefined;
getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined;
- getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
+ getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray;
getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined;
getBaseTypes(type: InterfaceType): BaseType[];
getBaseTypeOfLiteralType(type: Type): Type;
@@ -2629,11 +2648,6 @@ declare namespace ts {
writeType(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string;
writeSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags, writer?: EmitTextWriter): string;
writeTypePredicate(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string;
- /**
- * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead
- * This will be removed in a future version.
- */
- getSymbolDisplayBuilder(): SymbolDisplayBuilder;
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): Symbol[];
@@ -2675,7 +2689,7 @@ declare namespace ts {
*/
tryGetMemberInModuleExportsAndProperties(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
- getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined;
+ getSuggestionForNonexistentProperty(name: Identifier | string, containingType: Type): string | undefined;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
getSuggestionForNonexistentModule(node: Identifier, target: Symbol): string | undefined;
getBaseConstraintOfType(type: Type): Type | undefined;
@@ -2709,6 +2723,11 @@ declare namespace ts {
getSymbolCount(): number;
getTypeCount(): number;
isArrayLikeType(type: Type): boolean;
+ /**
+ * True if `contextualType` should not be considered for completions because
+ * e.g. it specifies `kind: "a"` and obj has `kind: "b"`.
+ */
+ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean;
/**
* For a union, will include a property if it's defined in *any* of the member types.
* So for `{ a } | { b }`, this will include both `a` and `b`.
@@ -2821,25 +2840,6 @@ declare namespace ts {
visitedSymbols: ReadonlyArray;
};
}
- /**
- * @deprecated
- */
- interface SymbolDisplayBuilder {
- /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
- /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
- /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
- /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- }
- /**
- * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString
- */
interface SymbolWriter extends SymbolTracker {
writeKeyword(text: string): void;
writeOperator(text: string): void;
@@ -2939,7 +2939,7 @@ declare namespace ts {
getNodeCheckFlags(node: Node): NodeCheckFlags;
isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean;
isLateBound(node: Declaration): node is LateBoundDeclaration;
- collectLinkedAliases(node: Identifier): Node[] | undefined;
+ collectLinkedAliases(node: Identifier, setVisibility?: boolean): Node[] | undefined;
isImplementationOfOverload(node: FunctionLike): boolean | undefined;
isRequiredInitializedParameter(node: ParameterDeclaration): boolean;
isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean;
@@ -3072,6 +3072,7 @@ declare namespace ts {
enumKind?: EnumKind;
originatingImport?: ImportDeclaration | ImportCall;
lateSymbol?: Symbol;
+ specifierCache?: Map;
}
enum EnumKind {
Numeric = 0,
@@ -3090,11 +3091,12 @@ declare namespace ts {
ContainsStatic = 512,
Late = 1024,
ReverseMapped = 2048,
+ OptionalParameter = 4096,
+ RestParameter = 8192,
Synthetic = 6
}
interface TransientSymbol extends Symbol, SymbolLinks {
checkFlags: CheckFlags;
- isRestParameter?: boolean;
}
interface ReverseMappedSymbol extends TransientSymbol {
propertyType: Type;
@@ -3195,6 +3197,7 @@ declare namespace ts {
hasSuperCall?: boolean;
superCall?: SuperCall;
switchTypes?: Type[];
+ jsxNamespace?: Symbol | false;
}
enum TypeFlags {
Any = 1,
@@ -3270,7 +3273,7 @@ declare namespace ts {
symbol: Symbol;
pattern?: DestructuringPattern;
aliasSymbol?: Symbol;
- aliasTypeArguments?: Type[];
+ aliasTypeArguments?: ReadonlyArray;
wildcardInstantiation?: Type;
}
interface IntrinsicType extends Type {
@@ -3311,6 +3314,12 @@ declare namespace ts {
}
interface ObjectType extends Type {
objectFlags: ObjectFlags;
+ members?: SymbolTable;
+ properties?: Symbol[];
+ callSignatures?: ReadonlyArray;
+ constructSignatures?: ReadonlyArray;
+ stringIndexInfo?: IndexInfo;
+ numberIndexInfo?: IndexInfo;
}
/** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */
interface InterfaceType extends ObjectType {
@@ -3341,7 +3350,7 @@ declare namespace ts {
*/
interface TypeReference extends ObjectType {
target: GenericType;
- typeArguments?: Type[];
+ typeArguments?: ReadonlyArray;
}
enum Variance {
Invariant = 0,
@@ -3354,6 +3363,14 @@ declare namespace ts {
instantiations: Map;
variances?: Variance[];
}
+ interface TupleType extends GenericType {
+ minLength: number;
+ hasRestElement: boolean;
+ associatedNames?: __String[];
+ }
+ interface TupleTypeReference extends TypeReference {
+ target: TupleType;
+ }
interface UnionOrIntersectionType extends Type {
types: Type[];
propertyCache: SymbolTable;
@@ -3391,10 +3408,8 @@ declare namespace ts {
interface ResolvedType extends ObjectType, UnionOrIntersectionType {
members: SymbolTable;
properties: Symbol[];
- callSignatures: Signature[];
- constructSignatures: Signature[];
- stringIndexInfo?: IndexInfo;
- numberIndexInfo?: IndexInfo;
+ callSignatures: ReadonlyArray;
+ constructSignatures: ReadonlyArray;
}
interface FreshObjectLiteralType extends ResolvedType {
regularType: ResolvedType;
@@ -3471,8 +3486,8 @@ declare namespace ts {
}
interface Signature {
declaration?: SignatureDeclaration | JSDocSignature;
- typeParameters?: TypeParameter[];
- parameters: Symbol[];
+ typeParameters?: ReadonlyArray;
+ parameters: ReadonlyArray;
thisParameter?: Symbol;
resolvedReturnType?: Type;
resolvedTypePredicate?: TypePredicate;
@@ -3538,7 +3553,7 @@ declare namespace ts {
}
type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary;
interface InferenceContext extends TypeMapper {
- typeParameters: TypeParameter[];
+ typeParameters: ReadonlyArray;
signature?: Signature;
inferences: InferenceInfo[];
flags: InferenceFlags;
@@ -3586,14 +3601,14 @@ declare namespace ts {
next?: DiagnosticMessageChain;
}
interface Diagnostic extends DiagnosticRelatedInformation {
- category: DiagnosticCategory;
/** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
reportsUnnecessary?: {};
- code: number;
source?: string;
relatedInformation?: DiagnosticRelatedInformation[];
}
interface DiagnosticRelatedInformation {
+ category: DiagnosticCategory;
+ code: number;
file: SourceFile | undefined;
start: number | undefined;
length: number | undefined;
@@ -4268,6 +4283,7 @@ declare namespace ts {
}
interface EmitHost extends ScriptReferenceHost, ModuleSpecifierResolutionHost {
getSourceFiles(): ReadonlyArray;
+ useCaseSensitiveFileNames(): boolean;
getCurrentDirectory(): string;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
getCommonSourceDirectory(): string;
@@ -4497,14 +4513,13 @@ declare namespace ts {
readFile?(path: string): string | undefined;
getSourceFiles?(): ReadonlyArray;
}
- /** @deprecated See comment on SymbolWriter */
interface SymbolTracker {
trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
reportInaccessibleThisError?(): void;
reportPrivateInBaseOfClassExpression?(propertyName: string): void;
reportInaccessibleUniqueSymbolError?(): void;
moduleResolverHost?: ModuleSpecifierResolutionHost;
- trackReferencedAmbientModule?(decl: ModuleDeclaration): void;
+ trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void;
}
interface TextSpan {
start: number;
@@ -4516,6 +4531,7 @@ declare namespace ts {
}
interface DiagnosticCollection {
add(diagnostic: Diagnostic): void;
+ lookup(diagnostic: Diagnostic): Diagnostic | undefined;
getGlobalDiagnostics(): Diagnostic[];
getDiagnostics(fileName: string): DiagnosticWithLocation[];
getDiagnostics(): Diagnostic[];
@@ -4921,7 +4937,6 @@ declare namespace ts {
An_object_literal_cannot_have_property_and_accessor_with_the_same_name: DiagnosticMessage;
An_export_assignment_cannot_have_modifiers: DiagnosticMessage;
Octal_literals_are_not_allowed_in_strict_mode: DiagnosticMessage;
- A_tuple_type_element_list_cannot_be_empty: DiagnosticMessage;
Variable_declaration_list_cannot_be_empty: DiagnosticMessage;
Digit_expected: DiagnosticMessage;
Hexadecimal_digit_expected: DiagnosticMessage;
@@ -5041,6 +5056,8 @@ declare namespace ts {
_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: DiagnosticMessage;
A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: DiagnosticMessage;
A_definite_assignment_assertion_is_not_permitted_in_this_context: DiagnosticMessage;
+ A_rest_element_must_be_last_in_a_tuple_type: DiagnosticMessage;
+ A_required_element_cannot_follow_an_optional_element: DiagnosticMessage;
with_statements_are_not_allowed_in_an_async_function_block: DiagnosticMessage;
await_expression_is_only_allowed_within_an_async_function: DiagnosticMessage;
can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: DiagnosticMessage;
@@ -5071,7 +5088,7 @@ declare namespace ts {
An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: DiagnosticMessage;
infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: DiagnosticMessage;
Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: DiagnosticMessage;
- Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here: DiagnosticMessage;
+ Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: DiagnosticMessage;
Type_arguments_cannot_be_used_here: DiagnosticMessage;
The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: DiagnosticMessage;
Duplicate_identifier_0: DiagnosticMessage;
@@ -5141,6 +5158,7 @@ declare namespace ts {
The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: DiagnosticMessage;
Operator_0_cannot_be_applied_to_types_1_and_2: DiagnosticMessage;
Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: DiagnosticMessage;
+ This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: DiagnosticMessage;
Type_parameter_name_cannot_be_0: DiagnosticMessage;
A_parameter_property_is_only_allowed_in_a_constructor_implementation: DiagnosticMessage;
A_rest_parameter_must_be_of_an_array_type: DiagnosticMessage;
@@ -5190,6 +5208,7 @@ declare namespace ts {
Class_0_incorrectly_extends_base_class_1: DiagnosticMessage;
Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: DiagnosticMessage;
Class_static_side_0_incorrectly_extends_base_class_static_side_1: DiagnosticMessage;
+ Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: DiagnosticMessage;
Class_0_incorrectly_implements_interface_1: DiagnosticMessage;
A_class_may_only_implement_another_class_or_interface: DiagnosticMessage;
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: DiagnosticMessage;
@@ -5337,6 +5356,9 @@ declare namespace ts {
Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: DiagnosticMessage;
Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: DiagnosticMessage;
Object_is_of_type_unknown: DiagnosticMessage;
+ Rest_signatures_are_incompatible: DiagnosticMessage;
+ Property_0_is_incompatible_with_rest_element_type: DiagnosticMessage;
+ A_rest_element_type_must_be_an_array_type: DiagnosticMessage;
JSX_element_attributes_type_0_may_not_be_a_union_type: DiagnosticMessage;
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: DiagnosticMessage;
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: DiagnosticMessage;
@@ -5423,6 +5445,8 @@ declare namespace ts {
Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: DiagnosticMessage;
Cannot_find_lib_definition_for_0: DiagnosticMessage;
Cannot_find_lib_definition_for_0_Did_you_mean_1: DiagnosticMessage;
+ _0_was_declared_here: DiagnosticMessage;
+ Property_0_is_used_before_its_initialization: DiagnosticMessage;
Import_declaration_0_is_using_private_name_1: DiagnosticMessage;
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: DiagnosticMessage;
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: DiagnosticMessage;
@@ -5722,6 +5746,10 @@ declare namespace ts {
Include_modules_imported_with_json_extension: DiagnosticMessage;
All_destructured_elements_are_unused: DiagnosticMessage;
All_variables_are_unused: DiagnosticMessage;
+ Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: DiagnosticMessage;
+ Conflicts_are_in_this_file: DiagnosticMessage;
+ _0_was_also_declared_here: DiagnosticMessage;
+ and_here: DiagnosticMessage;
Projects_to_reference: DiagnosticMessage;
Enable_project_compilation: DiagnosticMessage;
Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: DiagnosticMessage;
@@ -5753,6 +5781,8 @@ declare namespace ts {
Option_build_must_be_the_first_command_line_argument: DiagnosticMessage;
Options_0_and_1_cannot_be_combined: DiagnosticMessage;
Skipping_clean_because_not_all_projects_could_be_located: DiagnosticMessage;
+ The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: DiagnosticMessage;
+ The_expected_type_comes_from_this_index_signature: DiagnosticMessage;
Variable_0_implicitly_has_an_1_type: DiagnosticMessage;
Parameter_0_implicitly_has_an_1_type: DiagnosticMessage;
Member_0_implicitly_has_an_1_type: DiagnosticMessage;
@@ -5784,6 +5814,7 @@ declare namespace ts {
Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: DiagnosticMessage;
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: DiagnosticMessage;
Mapped_object_type_implicitly_has_an_any_template_type: DiagnosticMessage;
+ 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_0: DiagnosticMessage;
You_cannot_rename_this_element: DiagnosticMessage;
You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: DiagnosticMessage;
import_can_only_be_used_in_a_ts_file: DiagnosticMessage;
@@ -5928,6 +5959,10 @@ declare namespace ts {
Add_or_remove_braces_in_an_arrow_function: DiagnosticMessage;
Add_braces_to_arrow_function: DiagnosticMessage;
Remove_braces_from_arrow_function: DiagnosticMessage;
+ Convert_default_export_to_named_export: DiagnosticMessage;
+ Convert_named_export_to_default_export: DiagnosticMessage;
+ Add_missing_enum_member_0: DiagnosticMessage;
+ Add_all_missing_imports: DiagnosticMessage;
};
}
declare namespace ts {
@@ -6105,11 +6140,6 @@ declare namespace ts {
function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile): string;
function getTextOfConstantValue(value: string | number): string;
function escapeLeadingUnderscores(identifier: string): __String;
- /**
- * @deprecated Use `id.escapedText` to get the escaped text of an Identifier.
- * @param identifier The identifier to escape
- */
- function escapeIdentifier(identifier: string): string;
function makeIdentifierFromModuleName(moduleName: string): string;
function isBlockOrCatchScoped(declaration: Declaration): boolean;
function isCatchClauseVariableDeclarationOrBindingElement(declaration: Declaration): boolean;
@@ -6138,7 +6168,7 @@ declare namespace ts {
function isLateVisibilityPaintedStatement(node: Node): node is LateVisibilityPaintedStatement;
function isAnyImportOrReExport(node: Node): node is AnyImportOrReExport;
function getEnclosingBlockScopeContainer(node: Node): Node;
- function declarationNameToString(name: DeclarationName | QualifiedName): string;
+ function declarationNameToString(name: DeclarationName | QualifiedName | undefined): string;
function getNameFromIndexInfo(info: IndexInfo): string | undefined;
function getTextOfPropertyName(name: PropertyName): __String;
function entityNameToString(name: EntityNameOrEntityNameExpression): string;
@@ -6150,8 +6180,8 @@ declare namespace ts {
function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan;
function isExternalOrCommonJsModule(file: SourceFile): boolean;
function isJsonSourceFile(file: SourceFile): file is JsonSourceFile;
- function isConstEnumDeclaration(node: Node): boolean;
- function isConst(node: Node): boolean;
+ function isEnumConst(node: EnumDeclaration): boolean;
+ function isVarConst(node: VariableDeclaration | VariableDeclarationList): boolean;
function isLet(node: Node): boolean;
function isSuperCall(n: Node): n is SuperCall;
function isImportCall(n: Node): n is ImportCall;
@@ -6275,6 +6305,7 @@ declare namespace ts {
function isExportsIdentifier(node: Node): boolean;
function isModuleExportsPropertyAccessExpression(node: Node): boolean;
function getSpecialPropertyAssignmentKind(expr: BinaryExpression): SpecialPropertyAssignmentKind;
+ function getSpecialPropertyAccessKind(lhs: PropertyAccessExpression): SpecialPropertyAssignmentKind;
function getInitializerOfBinaryExpression(expr: BinaryExpression): Expression;
function isPrototypePropertyAssignment(node: Node): boolean;
function isSpecialPropertyDeclaration(expr: PropertyAccessExpression): boolean;
@@ -6325,7 +6356,8 @@ declare namespace ts {
function isIdentifierName(node: Identifier): boolean;
function isAliasSymbolDeclaration(node: Node): boolean;
function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean;
- function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments | undefined;
+ function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments | undefined;
+ function getClassExtendsHeritageElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments | undefined;
function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration): NodeArray | undefined;
/** Returns the node in an `extends` or `implements` clause of a class or interface. */
function getAllSuperTypeNodes(node: Node): ReadonlyArray;
@@ -6613,7 +6645,7 @@ declare namespace ts {
function getObjectFlags(type: Type): ObjectFlags;
function typeHasCallOrConstructSignatures(type: Type, checker: TypeChecker): boolean;
function forSomeAncestorDirectory(directory: string, callback: (directory: string) => boolean): boolean;
- function isUMDExportSymbol(symbol: Symbol | undefined): boolean | undefined;
+ function isUMDExportSymbol(symbol: Symbol | undefined): boolean;
function showModuleSpecifier({ moduleSpecifier }: ImportDeclaration): string;
function getLastChild(node: Node): Node | undefined;
/** Add a value to a set, and return true if it wasn't already present. */
@@ -6626,6 +6658,7 @@ declare namespace ts {
function textSpanEnd(span: TextSpan): number;
function textSpanIsEmpty(span: TextSpan): boolean;
function textSpanContainsPosition(span: TextSpan, position: number): boolean;
+ function textRangeContainsPositionInclusive(span: TextRange, position: number): boolean;
function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined;
@@ -6658,7 +6691,8 @@ declare namespace ts {
function isParameterPropertyDeclaration(node: Node): node is ParameterPropertyDeclaration;
function isEmptyBindingPattern(node: BindingName): node is BindingPattern;
function isEmptyBindingElement(node: BindingElement): boolean;
- function getCombinedModifierFlags(node: Node): ModifierFlags;
+ function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration;
+ function getCombinedModifierFlags(node: Declaration): ModifierFlags;
function getCombinedNodeFlags(node: Node): NodeFlags;
/**
* Checks to see if the locale is in the appropriate format,
@@ -6704,19 +6738,14 @@ declare namespace ts {
function unescapeLeadingUnderscores(identifier: __String): string;
function idText(identifier: Identifier): string;
function symbolName(symbol: Symbol): string;
- /**
- * Remove extra underscore from escaped identifier text content.
- * @deprecated Use `id.text` for the unescaped text.
- * @param identifier The escaped identifier text.
- * @returns The unescaped identifier text.
- */
- function unescapeIdentifier(id: string): string;
function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined;
/** @internal */
function isNamedDeclaration(node: Node): node is NamedDeclaration & {
name: DeclarationName;
};
- function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName;
+ /** @internal */
+ function getNonAssignedNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined;
+ function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined;
/**
* Gets the JSDoc parameter tags for the node if present.
*
@@ -6961,7 +6990,7 @@ declare namespace ts {
function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail;
function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken;
function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier;
- function isModifierKind(token: SyntaxKind): boolean;
+ function isModifierKind(token: SyntaxKind): token is Modifier["kind"];
function isParameterPropertyModifier(kind: SyntaxKind): boolean;
function isClassMemberModifier(idToken: SyntaxKind): boolean;
function isModifier(node: Node): node is Modifier;
@@ -7092,6 +7121,7 @@ declare namespace ts {
function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | undefined)[]): DiagnosticMessageChain;
function concatenateDiagnosticMessageChains(headChain: DiagnosticMessageChain, tailChain: DiagnosticMessageChain): DiagnosticMessageChain;
function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison;
+ function compareDiagnosticsSkipRelatedInformation(d1: Diagnostic, d2: Diagnostic): Comparison;
function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget;
function getEmitModuleKind(compilerOptions: {
module?: CompilerOptions["module"];
@@ -7283,7 +7313,7 @@ declare namespace ts {
function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison;
function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean;
function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
- function tryRemoveDirectoryPrefix(path: string, dirPath: string): string | undefined;
+ function tryRemoveDirectoryPrefix(path: string, dirPath: string, getCanonicalFileName: GetCanonicalFileName): string | undefined;
function hasExtension(fileName: string): boolean;
const commonPackageFolders: ReadonlyArray;
function getRegularExpressionForWildcard(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined;
@@ -7381,6 +7411,9 @@ declare namespace ts {
* (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
*/
function matchPatternOrExact(patternStrings: ReadonlyArray, candidate: string): string | Pattern | undefined;
+ type Mutable = {
+ -readonly [K in keyof T]: T[K];
+ };
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
@@ -7733,8 +7766,8 @@ declare namespace ts {
/** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
function createFileLevelUniqueName(text: string): Identifier;
/** Create a unique name generated for a node. */
- function getGeneratedNameForNode(node: Node): Identifier;
- function getGeneratedNameForNode(node: Node, flags: GeneratedIdentifierFlags): Identifier;
+ function getGeneratedNameForNode(node: Node | undefined): Identifier;
+ function getGeneratedNameForNode(node: Node | undefined, flags: GeneratedIdentifierFlags): Identifier;
function createToken(token: TKind): Token;
function createSuper(): SuperExpression;
function createThis(): ThisExpression & Token;
@@ -7790,7 +7823,11 @@ declare namespace ts {
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode;
- function updateTypleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode;
+ function updateTupleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode;
+ function createOptionalTypeNode(type: TypeNode): OptionalTypeNode;
+ function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode;
+ function createRestTypeNode(type: TypeNode): RestTypeNode;
+ function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode;
function createUnionTypeNode(types: ReadonlyArray): UnionTypeNode;
function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode;
function createIntersectionTypeNode(types: ReadonlyArray): IntersectionTypeNode;
@@ -7845,7 +7882,7 @@ declare namespace ts {
function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression;
function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression;
function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction;
- function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction;
+ /** @deprecated */ function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction;
function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction;
function createDelete(expression: Expression): DeleteExpression;
function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression;
@@ -7863,7 +7900,7 @@ declare namespace ts {
function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression;
function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression;
- function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
+ /** @deprecated */ function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression;
function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression;
function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression;
@@ -7891,13 +7928,16 @@ declare namespace ts {
function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
function createSemicolonClassElement(): SemicolonClassElement;
function createBlock(statements: ReadonlyArray, multiLine?: boolean): Block;
- function createExpressionStatement(expression: Expression): ExpressionStatement;
function updateBlock(node: Block, statements: ReadonlyArray): Block;
function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement;
function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement;
function createEmptyStatement(): EmptyStatement;
- function createStatement(expression: Expression): ExpressionStatement;
- function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement;
+ function createExpressionStatement(expression: Expression): ExpressionStatement;
+ function updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement;
+ /** @deprecated Use `createExpressionStatement` instead. */
+ const createStatement: typeof createExpressionStatement;
+ /** @deprecated Use `updateExpressionStatement` instead. */
+ const updateStatement: typeof updateExpressionStatement;
function createIf(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement;
function updateIf(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement;
function createDo(statement: Statement, expression: Expression): DoStatement;
@@ -8346,6 +8386,9 @@ declare namespace ts {
function parenthesizeElementTypeMembers(members: ReadonlyArray): NodeArray;
function parenthesizeTypeParameters(typeParameters: ReadonlyArray | undefined): MutableNodeArray | undefined;
function parenthesizeConciseBody(body: ConciseBody): ConciseBody;
+ function isCommaSequence(node: Expression): node is (BinaryExpression & {
+ operatorToken: Token;
+ }) | CommaListExpression;
enum OuterExpressionKinds {
Parentheses = 1,
Assertions = 2,
@@ -8576,17 +8619,6 @@ declare namespace ts.sourcemaps {
readonly lastSpan: SourceMapSpan;
}
function decodeMappings(map: SourceMapData): MappingsDecoder;
- function calculateDecodedMappings(map: SourceMapData, processPosition: (position: RawSourceMapPosition) => T, host?: {
- log?(s: string): void;
- }): T[];
- interface RawSourceMapPosition {
- emittedLine: number;
- emittedColumn: number;
- sourceLine: number;
- sourceColumn: number;
- sourceIndex: number;
- nameIndex?: number;
- }
}
declare namespace ts {
function getOriginalNodeId(node: Node): number;
@@ -8918,6 +8950,7 @@ declare namespace ts {
}
/** @internal */
function formatColorAndReset(text: string, formatStyle: string): string;
+ function formatLocation(file: SourceFile, start: number, host: FormatDiagnosticsHost, color?: typeof formatColorAndReset): string;
function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string;
/**
@@ -9265,9 +9298,9 @@ declare namespace ts {
}
declare namespace ts.moduleSpecifiers {
interface ModuleSpecifierPreferences {
- importModuleSpecifierPreference?: "relative" | "non-relative";
+ readonly importModuleSpecifierPreference?: "relative" | "non-relative";
}
- function getModuleSpecifier(compilerOptions: CompilerOptions, fromSourceFile: SourceFile, fromSourceFileName: string, toFileName: string, host: ModuleSpecifierResolutionHost, preferences?: ModuleSpecifierPreferences): string;
+ function getModuleSpecifier(compilerOptions: CompilerOptions, importingSourceFile: SourceFile, importingSourceFileName: Path, toFileName: string, host: ModuleSpecifierResolutionHost, files: ReadonlyArray, preferences?: ModuleSpecifierPreferences): string;
function getModuleSpecifiers(moduleSymbol: Symbol, compilerOptions: CompilerOptions, importingSourceFile: SourceFile, host: ModuleSpecifierResolutionHost, files: ReadonlyArray, preferences: ModuleSpecifierPreferences): ReadonlyArray>;
}
declare namespace ts {
@@ -9521,12 +9554,12 @@ declare namespace ts {
*/
interface UpToDate {
type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes;
- newestInputFileTime: Date;
- newestInputFileName: string;
- newestDeclarationFileContentChangedTime: Date;
- newestOutputFileTime: Date;
- newestOutputFileName: string;
- oldestOutputFileName: string;
+ newestInputFileTime?: Date;
+ newestInputFileName?: string;
+ newestDeclarationFileContentChangedTime?: Date;
+ newestOutputFileTime?: Date;
+ newestOutputFileName?: string;
+ oldestOutputFileName?: string;
}
/**
* One or more of the outputs of the project does not exist.
@@ -9829,8 +9862,8 @@ declare namespace ts {
getProperties(): Symbol[];
getProperty(propertyName: string): Symbol | undefined;
getApparentProperties(): Symbol[];
- getCallSignatures(): Signature[];
- getConstructSignatures(): Signature[];
+ getCallSignatures(): ReadonlyArray;
+ getConstructSignatures(): ReadonlyArray;
getStringIndexType(): Type | undefined;
getNumberIndexType(): Type | undefined;
getBaseTypes(): BaseType[] | undefined;
@@ -9859,7 +9892,7 @@ declare namespace ts {
version: string;
scriptSnapshot: IScriptSnapshot | undefined;
nameTable: UnderscoreEscapedMap | undefined;
- getNamedDeclarations(): Map;
+ getNamedDeclarations(): Map>;
getLineAndCharacterOfPosition(pos: number): LineAndCharacter;
getLineEndOfPosition(pos: number): number;
getLineStarts(): ReadonlyArray;
@@ -9956,7 +9989,7 @@ declare namespace ts {
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
- const defaultPreferences: UserPreferences;
+ const emptyOptions: {};
interface LanguageService {
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[];
@@ -9980,7 +10013,7 @@ declare namespace ts {
getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined;
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined;
getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined;
- getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems | undefined;
+ getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined;
getRenameInfo(fileName: string, position: number): RenameInfo;
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined;
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined;
@@ -10041,13 +10074,54 @@ declare namespace ts {
type OrganizeImportsScope = CombinedCodeFixScope;
type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
interface GetCompletionsAtPositionOptions extends UserPreferences {
- /** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */
+ /**
+ * If the editor is asking for completions because a certain character was typed
+ * (as opposed to when the user explicitly requested them) this should be set.
+ */
triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
includeInsertTextCompletions?: boolean;
}
+ type SignatureHelpTriggerCharacter = "," | "(" | "<";
+ type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")";
+ interface SignatureHelpItemsOptions {
+ triggerReason?: SignatureHelpTriggerReason;
+ }
+ type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason;
+ /**
+ * Signals that the user manually requested signature help.
+ * The language service will unconditionally attempt to provide a result.
+ */
+ interface SignatureHelpInvokedReason {
+ kind: "invoked";
+ triggerCharacter?: undefined;
+ }
+ /**
+ * Signals that the signature help request came from a user typing a character.
+ * Depending on the character and the syntactic context, the request may or may not be served a result.
+ */
+ interface SignatureHelpCharacterTypedReason {
+ kind: "characterTyped";
+ /**
+ * Character that was responsible for triggering signature help.
+ */
+ triggerCharacter: SignatureHelpTriggerCharacter;
+ }
+ /**
+ * Signals that this signature help request came from typing a character or moving the cursor.
+ * This should only occur if a signature help session was already active and the editor needs to see if it should adjust.
+ * The language service will unconditionally attempt to provide a result.
+ * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move.
+ */
+ interface SignatureHelpRetriggeredReason {
+ kind: "retrigger";
+ /**
+ * Character that was responsible for triggering signature help.
+ */
+ triggerCharacter?: SignatureHelpRetriggerCharacter;
+ }
interface ApplyCodeActionCommandResult {
successMessage: string;
}
@@ -10238,7 +10312,7 @@ declare namespace ts {
name: string;
kind: ScriptElementKind;
kindModifiers: string;
- matchKind: string;
+ matchKind: "exact" | "prefix" | "substring" | "camelCase";
isCaseSensitive: boolean;
fileName: string;
textSpan: TextSpan;
@@ -10695,11 +10769,13 @@ declare namespace ts {
}
function getLineStartPositionForPosition(position: number, sourceFile: SourceFileLike): number;
function rangeContainsRange(r1: TextRange, r2: TextRange): boolean;
+ function rangeContainsRangeExclusive(r1: TextRange, r2: TextRange): boolean;
function rangeContainsPosition(r: TextRange, pos: number): boolean;
function rangeContainsPositionExclusive(r: TextRange, pos: number): boolean;
function startEndContainsRange(start: number, end: number, range: TextRange): boolean;
function rangeContainsStartEnd(range: TextRange, start: number, end: number): boolean;
function rangeOverlapsWithStartEnd(r1: TextRange, start: number, end: number): boolean;
+ function nodeOverlapsWithStartEnd(node: Node, sourceFile: SourceFile, start: number, end: number): boolean;
function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number): boolean;
/**
* Assumes `candidate.start <= position` holds.
@@ -10718,9 +10794,9 @@ declare namespace ts {
* Returns the token if position is in [start, end).
* If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true
*/
- function getTouchingToken(sourceFile: SourceFile, position: number, includeJsDocComment: boolean, includePrecedingTokenAtEndPosition?: (n: Node) => boolean): Node;
+ function getTouchingToken(sourceFile: SourceFile, position: number, includePrecedingTokenAtEndPosition?: (n: Node) => boolean): Node;
/** Returns a token if position is in [start-of-leading-trivia, end) */
- function getTokenAtPosition(sourceFile: SourceFile, position: number, includeJsDocComment: boolean, includeEndPosition?: boolean): Node;
+ function getTokenAtPosition(sourceFile: SourceFile, position: number): Node;
/**
* The token on the left of the position is the token that strictly includes the position
* or sits to the left of the cursor if it is on a boundary. For example
@@ -10735,7 +10811,7 @@ declare namespace ts {
* Finds the rightmost token satisfying `token.end <= position`,
* excluding `JsxText` tokens containing only whitespace.
*/
- function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node, includeJsDoc?: boolean): Node | undefined;
+ function findPrecedingToken(position: number, sourceFile: SourceFile, startNode?: Node, excludeJsdoc?: boolean): Node | undefined;
function isInString(sourceFile: SourceFile, position: number, previousToken?: Node | undefined): boolean;
/**
* returns true if the position is in between the open and close elements of an JSX expression.
@@ -10754,8 +10830,8 @@ declare namespace ts {
* @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position)
* @param predicate Additional predicate to test on the comment range.
*/
- function isInComment(sourceFile: SourceFile, position: number, tokenAtPosition?: Node, predicate?: (c: CommentRange) => boolean): boolean;
- function hasDocComment(sourceFile: SourceFile, position: number): boolean | undefined;
+ function isInComment(sourceFile: SourceFile, position: number, tokenAtPosition?: Node): CommentRange | undefined;
+ function hasDocComment(sourceFile: SourceFile, position: number): boolean;
function getNodeModifiers(node: Node): string;
function getTypeArgumentOrTypeParameterList(node: Node): NodeArray | undefined;
function isComment(kind: SyntaxKind): boolean;
@@ -10794,6 +10870,7 @@ declare namespace ts {
Single = 0,
Double = 1
}
+ function quotePreferenceFromString(str: StringLiteral, sourceFile: SourceFile): QuotePreference;
function getQuotePreference(sourceFile: SourceFile, preferences: UserPreferences): QuotePreference;
function symbolNameNoDefault(symbol: Symbol): string | undefined;
function symbolEscapedNameNoDefault(symbol: Symbol): __String | undefined;
@@ -10810,14 +10887,32 @@ declare namespace ts {
*/
function getPropertySymbolsFromBaseTypes(symbol: Symbol, propertyName: string, checker: TypeChecker, cb: (symbol: Symbol) => T | undefined): T | undefined;
function isMemberSymbolInBaseType(memberSymbol: Symbol, checker: TypeChecker): boolean;
- class NodeSet {
+ interface ReadonlyNodeSet {
+ has(node: Node): boolean;
+ forEach(cb: (node: Node) => void): void;
+ some(pred: (node: Node) => boolean): boolean;
+ }
+ class NodeSet implements ReadonlyNodeSet {
private map;
add(node: Node): void;
has(node: Node): boolean;
forEach(cb: (node: Node) => void): void;
some(pred: (node: Node) => boolean): boolean;
}
+ interface ReadonlyNodeMap {
+ get(node: TNode): TValue | undefined;
+ has(node: TNode): boolean;
+ }
+ class NodeMap implements ReadonlyNodeMap {
+ private map;
+ get(node: TNode): TValue | undefined;
+ getOrUpdate(node: TNode, setValue: () => TValue): TValue;
+ set(node: TNode, value: TValue): void;
+ has(node: TNode): boolean;
+ forEach(cb: (value: TValue, node: TNode) => void): void;
+ }
function getParentNodeInSpan(node: Node | undefined, file: SourceFile, span: TextSpan): Node | undefined;
+ function findModifier(node: Node, kind: Modifier["kind"]): Modifier | undefined;
function insertImport(changes: textChanges.ChangeTracker, sourceFile: SourceFile, importDecl: Statement): void;
}
declare namespace ts {
@@ -10906,7 +11001,7 @@ declare namespace ts.Completions {
name: string;
source?: string;
}
- function getCompletionEntryDetails(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, host: LanguageServiceHost, formatContext: formatting.FormatContext, getCanonicalFileName: GetCanonicalFileName, preferences: UserPreferences, cancellationToken: CancellationToken): CompletionEntryDetails | undefined;
+ function getCompletionEntryDetails(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences, cancellationToken: CancellationToken): CompletionEntryDetails | undefined;
function getCompletionEntrySymbol(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier): Symbol | undefined;
}
declare namespace ts.DocumentHighlights {
@@ -10995,7 +11090,7 @@ declare namespace ts.FindAllReferences {
}
type ImportTracker = (exportSymbol: Symbol, exportInfo: ExportInfo, isForRename: boolean) => ImportsResult;
/** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */
- function createImportTracker(sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken): ImportTracker;
+ function createImportTracker(sourceFiles: ReadonlyArray, sourceFilesSet: ReadonlyMap, checker: TypeChecker, cancellationToken: CancellationToken | undefined): ImportTracker;
/** Info about an exported symbol to perform recursive search on. */
interface ExportInfo {
exportingModuleSymbol: Symbol;
@@ -11087,7 +11182,7 @@ declare namespace ts.FindAllReferences {
}
function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined;
function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number): ImplementationLocation[] | undefined;
- function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined;
+ function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number, options: Options | undefined): ReferenceEntry[] | undefined;
function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options?: Options, sourceFilesSet?: ReadonlyMap): Entry[] | undefined;
function toHighlightSpan(entry: Entry): {
fileName: string;
@@ -11098,9 +11193,11 @@ declare namespace ts.FindAllReferences {
declare namespace ts.FindAllReferences.Core {
/** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options?: Options, sourceFilesSet?: ReadonlyMap): SymbolAndEntries[] | undefined;
+ function eachExportReference(sourceFiles: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken | undefined, exportSymbol: Symbol, exportingModuleSymbol: Symbol, exportName: string, isDefaultExport: boolean, cb: (ref: Identifier) => void): void;
/** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
function isSymbolReferencedInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile): boolean;
function eachSymbolReferenceInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile, cb: (token: Identifier) => T): T | undefined;
+ function eachSignatureCall(signature: SignatureDeclaration, sourceFiles: ReadonlyArray, checker: TypeChecker, cb: (call: CallExpression) => void): void;
/**
* Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations
* of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class
@@ -11114,6 +11211,9 @@ declare namespace ts.FindAllReferences.Core {
}
declare namespace ts {
function getEditsForFileRename(program: Program, oldFileOrDirPath: string, newFileOrDirPath: string, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): ReadonlyArray;
+ /** If 'path' refers to an old directory, returns path in the new directory. */
+ type PathUpdater = (path: string) => string | undefined;
+ function getPathUpdater(oldFileOrDirPath: string, newFileOrDirPath: string, getCanonicalFileName: GetCanonicalFileName): PathUpdater;
}
declare namespace ts.GoToDefinition {
function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): DefinitionInfo[] | undefined;
@@ -11211,10 +11311,10 @@ declare namespace ts {
function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo;
}
declare namespace ts.Rename {
- function getRenameInfo(typeChecker: TypeChecker, defaultLibFileName: string, getCanonicalFileName: GetCanonicalFileName, sourceFile: SourceFile, position: number): RenameInfo;
+ function getRenameInfo(program: Program, sourceFile: SourceFile, position: number): RenameInfo;
}
declare namespace ts.SignatureHelp {
- function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, cancellationToken: CancellationToken): SignatureHelpItems | undefined;
+ function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, triggerReason: SignatureHelpTriggerReason | undefined, cancellationToken: CancellationToken): SignatureHelpItems | undefined;
interface ArgumentInfoForCompletions {
readonly invocation: CallLikeExpression;
readonly argumentIndex: number;
@@ -11362,8 +11462,8 @@ declare namespace ts.formatting {
/**
* @param precedingToken pass `null` if preceding token was already computed and result was `undefined`.
*/
- function getRangeOfEnclosingComment(sourceFile: SourceFile, position: number, onlyMultiLine: boolean, precedingToken?: Node | null, // tslint:disable-line:no-null-keyword
- tokenAtPosition?: Node, predicate?: (c: CommentRange) => boolean): CommentRange | undefined;
+ function getRangeOfEnclosingComment(sourceFile: SourceFile, position: number, precedingToken?: Node | null, // tslint:disable-line:no-null-keyword
+ tokenAtPosition?: Node): CommentRange | undefined;
function getIndentationString(indentation: number, options: EditorSettings): string;
}
declare namespace ts.formatting {
@@ -11474,18 +11574,17 @@ declare namespace ts.textChanges {
private readonly formatContext;
private readonly changes;
private readonly newFiles;
- private readonly deletedNodesInLists;
private readonly classesWithNodesInsertedAtStart;
+ private readonly deletedNodes;
static fromContext(context: TextChangesContext): ChangeTracker;
static with(context: TextChangesContext, cb: (tracker: ChangeTracker) => void): FileTextChanges[];
/** Public for tests only. Other callers should use `ChangeTracker.with`. */
constructor(newLineCharacter: string, formatContext: formatting.FormatContext);
deleteRange(sourceFile: SourceFile, range: TextRange): this;
- /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
- deleteNode(sourceFile: SourceFile, node: Node, options?: ConfigurableStartEnd): this;
+ delete(sourceFile: SourceFile, node: Node): void;
+ deleteModifier(sourceFile: SourceFile, modifier: Modifier): void;
deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options?: ConfigurableStartEnd): this;
deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options?: ConfigurableStartEnd): void;
- deleteNodeInList(sourceFile: SourceFile, node: Node): this;
replaceRange(sourceFile: SourceFile, range: TextRange, newNode: Node, options?: InsertNodeOptions): this;
replaceNode(sourceFile: SourceFile, oldNode: Node, newNode: Node, options?: ChangeNodeOptions): this;
replaceNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, newNode: Node, options?: ChangeNodeOptions): void;
@@ -11494,7 +11593,7 @@ declare namespace ts.textChanges {
replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options?: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd): this;
private nextCommaToken;
replacePropertyAssignment(sourceFile: SourceFile, oldNode: PropertyAssignment, newNode: PropertyAssignment): this;
- private insertNodeAt;
+ insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options?: InsertNodeOptions): void;
private insertNodesAt;
insertNodeAtTopOfFile(sourceFile: SourceFile, newNode: Statement, blankLineBetween: boolean): void;
insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween?: boolean): void;
@@ -11514,6 +11613,7 @@ declare namespace ts.textChanges {
private getInsertNodeAtClassStartPrefixSuffix;
insertNodeAfterComma(sourceFile: SourceFile, after: Node, newNode: Node): void;
insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node): void;
+ insertNodeAtEndOfList(sourceFile: SourceFile, list: NodeArray, newNode: Node): void;
insertNodesAfter(sourceFile: SourceFile, after: Node, newNodes: ReadonlyArray): void;
private insertNodeAfterWorker;
private getInsertNodeAfterOptions;
@@ -11527,7 +11627,7 @@ declare namespace ts.textChanges {
*/
insertNodeInListAfter(sourceFile: SourceFile, after: Node, newNode: Node, containingList?: NodeArray | undefined): this;
private finishClassesWithNodesInsertedAtStart;
- private finishTrailingCommaAfterDeletingNodesInList;
+ private finishDeleteDeclarations;
/**
* Note: after calling this, the TextChanges object must be discarded!
* @param validate only for tests
@@ -11538,14 +11638,16 @@ declare namespace ts.textChanges {
createNewFile(oldFile: SourceFile, fileName: string, statements: ReadonlyArray): void;
}
type ValidateNonFormattedText = (node: Node, text: string) => void;
- function applyChanges(text: string, changes: TextChange[]): string;
+ function applyChanges(text: string, changes: ReadonlyArray): string;
function isValidLocationToAddComment(sourceFile: SourceFile, position: number): boolean;
+ /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
+ function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options?: ConfigurableStartEnd): void;
}
declare namespace ts {
interface CodeFixRegistration {
- errorCodes: number[];
+ errorCodes: ReadonlyArray;
getCodeActions(context: CodeFixContext): CodeFixAction[] | undefined;
- fixIds?: string[];
+ fixIds?: ReadonlyArray;
getAllCodeActions?(context: CodeFixAllContext): CombinedCodeActions;
}
interface CodeFixContextBase extends textChanges.TextChangesContext {
@@ -11569,8 +11671,10 @@ declare namespace ts {
function getSupportedErrorCodes(): string[];
function getFixes(context: CodeFixContext): CodeFixAction[];
function getAllFixes(context: CodeFixAllContext): CombinedCodeActions;
+ function createCombinedCodeActions(changes: FileTextChanges[], commands?: CodeActionCommand[]): CombinedCodeActions;
function createFileTextChanges(fileName: string, textChanges: TextChange[]): FileTextChanges;
function codeFixAll(context: CodeFixAllContext, errorCodes: number[], use: (changes: textChanges.ChangeTracker, error: DiagnosticWithLocation, commands: Push) => void): CombinedCodeActions;
+ function eachDiagnostic({ program, sourceFile, cancellationToken }: CodeFixAllContext, errorCodes: ReadonlyArray, cb: (diag: DiagnosticWithLocation) => void): void;
}
}
declare namespace ts {
@@ -11611,7 +11715,8 @@ declare namespace ts.codefix {
declare namespace ts.codefix {
}
declare namespace ts.codefix {
- function getImportCompletionAction(exportedSymbol: Symbol, moduleSymbol: Symbol, sourceFile: SourceFile, symbolName: string, host: LanguageServiceHost, program: Program, checker: TypeChecker, compilerOptions: CompilerOptions, allSourceFiles: ReadonlyArray, formatContext: formatting.FormatContext, getCanonicalFileName: GetCanonicalFileName, symbolToken: Node | undefined, preferences: UserPreferences): {
+ const importFixId = "fixMissingImport";
+ function getImportCompletionAction(exportedSymbol: Symbol, moduleSymbol: Symbol, sourceFile: SourceFile, symbolName: string, host: LanguageServiceHost, program: Program, checker: TypeChecker, allSourceFiles: ReadonlyArray, formatContext: formatting.FormatContext, symbolToken: Node | undefined, preferences: UserPreferences): {
readonly moduleSpecifier: string;
readonly codeAction: CodeAction;
};
@@ -11655,7 +11760,7 @@ declare namespace ts.codefix {
* @returns Empty string iff there are no member insertions.
*/
function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray, checker: TypeChecker, preferences: UserPreferences, out: (node: ClassElement) => void): void;
- function createMethodFromCallExpression({ typeArguments, arguments: args, parent: parent }: CallExpression, methodName: string, inJs: boolean, makeStatic: boolean, preferences: UserPreferences): MethodDeclaration;
+ function createMethodFromCallExpression(context: CodeFixContextBase, { typeArguments, arguments: args, parent: parent }: CallExpression, methodName: string, inJs: boolean, makeStatic: boolean, preferences: UserPreferences): MethodDeclaration;
}
declare namespace ts.codefix {
}
@@ -11671,7 +11776,9 @@ declare namespace ts.codefix {
}
declare namespace ts.codefix {
}
-declare namespace ts.refactor.generateGetAccessorAndSetAccessor {
+declare namespace ts.refactor {
+}
+declare namespace ts.refactor {
}
declare namespace ts.refactor.extractSymbol {
/**
@@ -11867,7 +11974,7 @@ declare namespace ts {
*/
readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
/**
- * Read arbitary text files on disk, i.e. when resolution procedure needs the content of 'package.json' to determine location of bundled typings for node modules
+ * Read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json' to determine location of bundled typings for node modules
*/
readFile(fileName: string): string | undefined;
realpath?(path: string): string;
@@ -11905,7 +12012,7 @@ declare namespace ts {
getQuickInfoAtPosition(fileName: string, position: number): string;
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string;
getBreakpointStatementAtPosition(fileName: string, position: number): string;
- getSignatureHelpItems(fileName: string, position: number): string;
+ getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): string;
/**
* Returns a JSON-encoded value of the type:
* { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } }
@@ -12204,6 +12311,7 @@ declare namespace ts.server.protocol {
Change = "change",
Close = "close",
Completions = "completions",
+ CompletionInfo = "completionInfo",
CompletionsFull = "completions-full",
CompletionDetails = "completionEntryDetails",
CompletionDetailsFull = "completionEntryDetails-full",
@@ -12467,7 +12575,7 @@ declare namespace ts.server.protocol {
command: CommandTypes.GetEditsForFileRename;
arguments: GetEditsForFileRenameRequestArgs;
}
- interface GetEditsForFileRenameRequestArgs extends FileRequestArgs {
+ interface GetEditsForFileRenameRequestArgs {
readonly oldFilePath: string;
readonly newFilePath: string;
}
@@ -12905,6 +13013,15 @@ declare namespace ts.server.protocol {
interface CompletionsResponse extends Response {
body?: CompletionEntry[];
}
+ interface CompletionInfoResponse extends Response {
+ body?: CompletionInfo;
+ }
+ interface CompletionInfo {
+ readonly isGlobalCompletion: boolean;
+ readonly isMemberCompletion: boolean;
+ readonly isNewIdentifierLocation: boolean;
+ readonly entries: ReadonlyArray;
+ }
interface CompletionDetailsResponse extends Response {
body?: CompletionEntryDetails[];
}
@@ -12930,7 +13047,23 @@ declare namespace ts.server.protocol {
argumentIndex: number;
argumentCount: number;
}
+ type SignatureHelpTriggerCharacter = "," | "(" | "<";
+ type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")";
interface SignatureHelpRequestArgs extends FileLocationRequestArgs {
+ triggerReason?: SignatureHelpTriggerReason;
+ }
+ type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason;
+ interface SignatureHelpInvokedReason {
+ kind: "invoked";
+ triggerCharacter?: undefined;
+ }
+ interface SignatureHelpCharacterTypedReason {
+ kind: "characterTyped";
+ triggerCharacter: SignatureHelpTriggerCharacter;
+ }
+ interface SignatureHelpRetriggeredReason {
+ kind: "retrigger";
+ triggerCharacter?: SignatureHelpRetriggerCharacter;
}
interface SignatureHelpRequest extends FileLocationRequest {
command: CommandTypes.SignatureHelp;
@@ -13003,6 +13136,8 @@ declare namespace ts.server.protocol {
fileName: string;
}
interface DiagnosticRelatedInformation {
+ category: string;
+ code: number;
message: string;
span?: FileSpan;
}
@@ -13066,15 +13201,12 @@ declare namespace ts.server.protocol {
command: CommandTypes.Navto;
arguments: NavtoRequestArgs;
}
- interface NavtoItem {
+ interface NavtoItem extends FileSpan {
name: string;
kind: ScriptElementKind;
- matchKind?: string;
- isCaseSensitive?: boolean;
+ matchKind: string;
+ isCaseSensitive: boolean;
kindModifiers?: string;
- file: string;
- start: Location;
- end: Location;
containerName?: string;
containerKind?: ScriptElementKind;
}
@@ -13312,18 +13444,21 @@ declare namespace ts.server.protocol {
}
}
declare namespace ts.server {
+ interface ScriptInfoVersion {
+ svc: number;
+ text: number;
+ }
class TextStorage {
private readonly host;
private readonly fileName;
+ version: ScriptInfoVersion;
private svc;
- private svcVersion;
private text;
private lineMap;
- private textVersion;
isOpen: boolean;
private ownFileText;
private pendingReloadFromDisk;
- constructor(host: ServerHost, fileName: NormalizedPath);
+ constructor(host: ServerHost, fileName: NormalizedPath, initialVersion?: ScriptInfoVersion);
getVersion(): string;
hasScriptVersionCache_TestOnly(): boolean;
useScriptVersionCache_TestOnly(): void;
@@ -13363,7 +13498,8 @@ declare namespace ts.server {
readonly isDynamic: boolean;
private realpath;
cacheSourceFile: DocumentRegistrySourceFileCache;
- constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path);
+ constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: ScriptInfoVersion);
+ getVersion(): ScriptInfoVersion;
isDynamicOrHasMixedContent(): boolean;
isScriptOpen(): boolean;
open(newText: string): void;
@@ -13773,6 +13909,7 @@ declare namespace ts.server {
readonly typingsCache: TypingsCache;
readonly documentRegistry: DocumentRegistry;
private readonly filenameToScriptInfo;
+ private readonly filenameToScriptInfoVersion;
private readonly allJsFilesForOpenFileTelemetry;
readonly realpathToScriptInfos: MultiMap | undefined;
private readonly externalProjectToConfiguredProjectMap;
@@ -13830,11 +13967,17 @@ declare namespace ts.server {
private delayUpdateProjectGraphs;
setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void;
findProject(projectName: string): Project | undefined;
+ forEachProject(cb: (project: Project) => void): void;
getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined;
+ tryGetDefaultProjectForFile(fileName: NormalizedPath): Project | undefined;
+ ensureDefaultProjectForFile(fileName: NormalizedPath): Project;
+ private doEnsureDefaultProjectForFile;
getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined;
private ensureProjectStructuresUptoDate;
getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings;
getPreferences(file: NormalizedPath): UserPreferences;
+ getHostFormatCodeOptions(): FormatCodeSettings;
+ getHostPreferences(): UserPreferences;
private onSourceFileChanged;
private handleDeletedFile;
watchWildcardDirectory(directory: Path, flags: WatchDirectoryFlags, project: ConfiguredProject): FileWatcher;
@@ -14065,6 +14208,7 @@ declare namespace ts.server {
private mapCodeAction;
private mapCodeFixAction;
private mapTextChangesToCodeEdits;
+ private mapTextChangeToCodeEdit;
private convertTextChangeToCodeEdit;
private getBraceMatching;
private getDiagnosticsForProject;
@@ -14081,6 +14225,8 @@ declare namespace ts.server {
onMessage(message: string): void;
private getFormatOptions;
private getPreferences;
+ private getHostFormatOptions;
+ private getHostPreferences;
}
interface HandlerResponse {
response?: {};
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index d9addcbcdbf..440e7824b60 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -242,144 +242,147 @@ declare namespace ts {
TypeLiteral = 166,
ArrayType = 167,
TupleType = 168,
- UnionType = 169,
- IntersectionType = 170,
- ConditionalType = 171,
- InferType = 172,
- ParenthesizedType = 173,
- ThisType = 174,
- TypeOperator = 175,
- IndexedAccessType = 176,
- MappedType = 177,
- LiteralType = 178,
- ImportType = 179,
- ObjectBindingPattern = 180,
- ArrayBindingPattern = 181,
- BindingElement = 182,
- ArrayLiteralExpression = 183,
- ObjectLiteralExpression = 184,
- PropertyAccessExpression = 185,
- ElementAccessExpression = 186,
- CallExpression = 187,
- NewExpression = 188,
- TaggedTemplateExpression = 189,
- TypeAssertionExpression = 190,
- ParenthesizedExpression = 191,
- FunctionExpression = 192,
- ArrowFunction = 193,
- DeleteExpression = 194,
- TypeOfExpression = 195,
- VoidExpression = 196,
- AwaitExpression = 197,
- PrefixUnaryExpression = 198,
- PostfixUnaryExpression = 199,
- BinaryExpression = 200,
- ConditionalExpression = 201,
- TemplateExpression = 202,
- YieldExpression = 203,
- SpreadElement = 204,
- ClassExpression = 205,
- OmittedExpression = 206,
- ExpressionWithTypeArguments = 207,
- AsExpression = 208,
- NonNullExpression = 209,
- MetaProperty = 210,
- TemplateSpan = 211,
- SemicolonClassElement = 212,
- Block = 213,
- VariableStatement = 214,
- EmptyStatement = 215,
- ExpressionStatement = 216,
- IfStatement = 217,
- DoStatement = 218,
- WhileStatement = 219,
- ForStatement = 220,
- ForInStatement = 221,
- ForOfStatement = 222,
- ContinueStatement = 223,
- BreakStatement = 224,
- ReturnStatement = 225,
- WithStatement = 226,
- SwitchStatement = 227,
- LabeledStatement = 228,
- ThrowStatement = 229,
- TryStatement = 230,
- DebuggerStatement = 231,
- VariableDeclaration = 232,
- VariableDeclarationList = 233,
- FunctionDeclaration = 234,
- ClassDeclaration = 235,
- InterfaceDeclaration = 236,
- TypeAliasDeclaration = 237,
- EnumDeclaration = 238,
- ModuleDeclaration = 239,
- ModuleBlock = 240,
- CaseBlock = 241,
- NamespaceExportDeclaration = 242,
- ImportEqualsDeclaration = 243,
- ImportDeclaration = 244,
- ImportClause = 245,
- NamespaceImport = 246,
- NamedImports = 247,
- ImportSpecifier = 248,
- ExportAssignment = 249,
- ExportDeclaration = 250,
- NamedExports = 251,
- ExportSpecifier = 252,
- MissingDeclaration = 253,
- ExternalModuleReference = 254,
- JsxElement = 255,
- JsxSelfClosingElement = 256,
- JsxOpeningElement = 257,
- JsxClosingElement = 258,
- JsxFragment = 259,
- JsxOpeningFragment = 260,
- JsxClosingFragment = 261,
- JsxAttribute = 262,
- JsxAttributes = 263,
- JsxSpreadAttribute = 264,
- JsxExpression = 265,
- CaseClause = 266,
- DefaultClause = 267,
- HeritageClause = 268,
- CatchClause = 269,
- PropertyAssignment = 270,
- ShorthandPropertyAssignment = 271,
- SpreadAssignment = 272,
- EnumMember = 273,
- SourceFile = 274,
- Bundle = 275,
- UnparsedSource = 276,
- InputFiles = 277,
- JSDocTypeExpression = 278,
- JSDocAllType = 279,
- JSDocUnknownType = 280,
- JSDocNullableType = 281,
- JSDocNonNullableType = 282,
- JSDocOptionalType = 283,
- JSDocFunctionType = 284,
- JSDocVariadicType = 285,
- JSDocComment = 286,
- JSDocTypeLiteral = 287,
- JSDocSignature = 288,
- JSDocTag = 289,
- JSDocAugmentsTag = 290,
- JSDocClassTag = 291,
- JSDocCallbackTag = 292,
- JSDocParameterTag = 293,
- JSDocReturnTag = 294,
- JSDocThisTag = 295,
- JSDocTypeTag = 296,
- JSDocTemplateTag = 297,
- JSDocTypedefTag = 298,
- JSDocPropertyTag = 299,
- SyntaxList = 300,
- NotEmittedStatement = 301,
- PartiallyEmittedExpression = 302,
- CommaListExpression = 303,
- MergeDeclarationMarker = 304,
- EndOfDeclarationMarker = 305,
- Count = 306,
+ OptionalType = 169,
+ RestType = 170,
+ UnionType = 171,
+ IntersectionType = 172,
+ ConditionalType = 173,
+ InferType = 174,
+ ParenthesizedType = 175,
+ ThisType = 176,
+ TypeOperator = 177,
+ IndexedAccessType = 178,
+ MappedType = 179,
+ LiteralType = 180,
+ ImportType = 181,
+ ObjectBindingPattern = 182,
+ ArrayBindingPattern = 183,
+ BindingElement = 184,
+ ArrayLiteralExpression = 185,
+ ObjectLiteralExpression = 186,
+ PropertyAccessExpression = 187,
+ ElementAccessExpression = 188,
+ CallExpression = 189,
+ NewExpression = 190,
+ TaggedTemplateExpression = 191,
+ TypeAssertionExpression = 192,
+ ParenthesizedExpression = 193,
+ FunctionExpression = 194,
+ ArrowFunction = 195,
+ DeleteExpression = 196,
+ TypeOfExpression = 197,
+ VoidExpression = 198,
+ AwaitExpression = 199,
+ PrefixUnaryExpression = 200,
+ PostfixUnaryExpression = 201,
+ BinaryExpression = 202,
+ ConditionalExpression = 203,
+ TemplateExpression = 204,
+ YieldExpression = 205,
+ SpreadElement = 206,
+ ClassExpression = 207,
+ OmittedExpression = 208,
+ ExpressionWithTypeArguments = 209,
+ AsExpression = 210,
+ NonNullExpression = 211,
+ MetaProperty = 212,
+ SyntheticExpression = 213,
+ TemplateSpan = 214,
+ SemicolonClassElement = 215,
+ Block = 216,
+ VariableStatement = 217,
+ EmptyStatement = 218,
+ ExpressionStatement = 219,
+ IfStatement = 220,
+ DoStatement = 221,
+ WhileStatement = 222,
+ ForStatement = 223,
+ ForInStatement = 224,
+ ForOfStatement = 225,
+ ContinueStatement = 226,
+ BreakStatement = 227,
+ ReturnStatement = 228,
+ WithStatement = 229,
+ SwitchStatement = 230,
+ LabeledStatement = 231,
+ ThrowStatement = 232,
+ TryStatement = 233,
+ DebuggerStatement = 234,
+ VariableDeclaration = 235,
+ VariableDeclarationList = 236,
+ FunctionDeclaration = 237,
+ ClassDeclaration = 238,
+ InterfaceDeclaration = 239,
+ TypeAliasDeclaration = 240,
+ EnumDeclaration = 241,
+ ModuleDeclaration = 242,
+ ModuleBlock = 243,
+ CaseBlock = 244,
+ NamespaceExportDeclaration = 245,
+ ImportEqualsDeclaration = 246,
+ ImportDeclaration = 247,
+ ImportClause = 248,
+ NamespaceImport = 249,
+ NamedImports = 250,
+ ImportSpecifier = 251,
+ ExportAssignment = 252,
+ ExportDeclaration = 253,
+ NamedExports = 254,
+ ExportSpecifier = 255,
+ MissingDeclaration = 256,
+ ExternalModuleReference = 257,
+ JsxElement = 258,
+ JsxSelfClosingElement = 259,
+ JsxOpeningElement = 260,
+ JsxClosingElement = 261,
+ JsxFragment = 262,
+ JsxOpeningFragment = 263,
+ JsxClosingFragment = 264,
+ JsxAttribute = 265,
+ JsxAttributes = 266,
+ JsxSpreadAttribute = 267,
+ JsxExpression = 268,
+ CaseClause = 269,
+ DefaultClause = 270,
+ HeritageClause = 271,
+ CatchClause = 272,
+ PropertyAssignment = 273,
+ ShorthandPropertyAssignment = 274,
+ SpreadAssignment = 275,
+ EnumMember = 276,
+ SourceFile = 277,
+ Bundle = 278,
+ UnparsedSource = 279,
+ InputFiles = 280,
+ JSDocTypeExpression = 281,
+ JSDocAllType = 282,
+ JSDocUnknownType = 283,
+ JSDocNullableType = 284,
+ JSDocNonNullableType = 285,
+ JSDocOptionalType = 286,
+ JSDocFunctionType = 287,
+ JSDocVariadicType = 288,
+ JSDocComment = 289,
+ JSDocTypeLiteral = 290,
+ JSDocSignature = 291,
+ JSDocTag = 292,
+ JSDocAugmentsTag = 293,
+ JSDocClassTag = 294,
+ JSDocCallbackTag = 295,
+ JSDocParameterTag = 296,
+ JSDocReturnTag = 297,
+ JSDocThisTag = 298,
+ JSDocTypeTag = 299,
+ JSDocTemplateTag = 300,
+ JSDocTypedefTag = 301,
+ JSDocPropertyTag = 302,
+ SyntaxList = 303,
+ NotEmittedStatement = 304,
+ PartiallyEmittedExpression = 305,
+ CommaListExpression = 306,
+ MergeDeclarationMarker = 307,
+ EndOfDeclarationMarker = 308,
+ Count = 309,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -391,7 +394,7 @@ declare namespace ts {
FirstFutureReservedWord = 108,
LastFutureReservedWord = 116,
FirstTypeNode = 161,
- LastTypeNode = 179,
+ LastTypeNode = 181,
FirstPunctuation = 17,
LastPunctuation = 70,
FirstToken = 0,
@@ -405,10 +408,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 146,
- FirstJSDocNode = 278,
- LastJSDocNode = 299,
- FirstJSDocTagNode = 289,
- LastJSDocTagNode = 299
+ FirstJSDocNode = 281,
+ LastJSDocNode = 302,
+ FirstJSDocTagNode = 292,
+ LastJSDocTagNode = 302
}
enum NodeFlags {
None = 0,
@@ -767,6 +770,14 @@ declare namespace ts {
kind: SyntaxKind.TupleType;
elementTypes: NodeArray;
}
+ interface OptionalTypeNode extends TypeNode {
+ kind: SyntaxKind.OptionalType;
+ type: TypeNode;
+ }
+ interface RestTypeNode extends TypeNode {
+ kind: SyntaxKind.RestType;
+ type: TypeNode;
+ }
type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode;
interface UnionTypeNode extends TypeNode {
kind: SyntaxKind.UnionType;
@@ -891,6 +902,11 @@ declare namespace ts {
asteriskToken?: AsteriskToken;
expression?: Expression;
}
+ interface SyntheticExpression extends Expression {
+ kind: SyntaxKind.SyntheticExpression;
+ isSpread: boolean;
+ type: Type;
+ }
type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken;
type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken;
type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator;
@@ -1105,7 +1121,10 @@ declare namespace ts {
}
type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute;
- type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression;
+ type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess;
+ interface JsxTagNamePropertyAccess extends PropertyAccessExpression {
+ expression: JsxTagNameExpression;
+ }
interface JsxAttributes extends ObjectLiteralExpressionBase {
parent: JsxOpeningLikeElement;
}
@@ -1780,6 +1799,7 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
+ isSourceFileDefaultLibrary(file: SourceFile): boolean;
getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
}
interface ResolvedProjectReference {
@@ -1818,7 +1838,6 @@ declare namespace ts {
inputSourceFileNames: string[];
sourceMapNames?: string[];
sourceMapMappings: string;
- sourceMapDecodedMappings: SourceMapSpan[];
}
/** Return code used by getEmitOutput function to indicate status of the function */
enum ExitStatus {
@@ -1838,7 +1857,7 @@ declare namespace ts {
getPropertiesOfType(type: Type): Symbol[];
getPropertyOfType(type: Type, propertyName: string): Symbol | undefined;
getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined;
- getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
+ getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray;
getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined;
getBaseTypes(type: InterfaceType): BaseType[];
getBaseTypeOfLiteralType(type: Type): Type;
@@ -1889,11 +1908,6 @@ declare namespace ts {
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string;
typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
- /**
- * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead
- * This will be removed in a future version.
- */
- getSymbolDisplayBuilder(): SymbolDisplayBuilder;
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): Symbol[];
@@ -1920,7 +1934,7 @@ declare namespace ts {
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
- getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined;
+ getSuggestionForNonexistentProperty(name: Identifier | string, containingType: Type): string | undefined;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
getSuggestionForNonexistentModule(node: Identifier, target: Symbol): string | undefined;
getBaseConstraintOfType(type: Type): Type | undefined;
@@ -1992,39 +2006,6 @@ declare namespace ts {
AllowAnyNodeKind = 4,
UseAliasDefinedOutsideCurrentScope = 8
}
- /**
- * @deprecated
- */
- interface SymbolDisplayBuilder {
- /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
- /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
- /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
- /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
- }
- /**
- * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString
- */
- interface SymbolWriter extends SymbolTracker {
- writeKeyword(text: string): void;
- writeOperator(text: string): void;
- writePunctuation(text: string): void;
- writeSpace(text: string): void;
- writeStringLiteral(text: string): void;
- writeParameter(text: string): void;
- writeProperty(text: string): void;
- writeSymbol(text: string, symbol: Symbol): void;
- writeLine(): void;
- increaseIndent(): void;
- decreaseIndent(): void;
- clear(): void;
- }
enum TypePredicateKind {
This = 0,
Identifier = 1
@@ -2214,7 +2195,7 @@ declare namespace ts {
symbol: Symbol;
pattern?: DestructuringPattern;
aliasSymbol?: Symbol;
- aliasTypeArguments?: Type[];
+ aliasTypeArguments?: ReadonlyArray;
}
interface LiteralType extends Type {
value: string | number;
@@ -2279,10 +2260,18 @@ declare namespace ts {
*/
interface TypeReference extends ObjectType {
target: GenericType;
- typeArguments?: Type[];
+ typeArguments?: ReadonlyArray;
}
interface GenericType extends InterfaceType, TypeReference {
}
+ interface TupleType extends GenericType {
+ minLength: number;
+ hasRestElement: boolean;
+ associatedNames?: __String[];
+ }
+ interface TupleTypeReference extends TypeReference {
+ target: TupleType;
+ }
interface UnionOrIntersectionType extends Type {
types: Type[];
}
@@ -2339,8 +2328,8 @@ declare namespace ts {
}
interface Signature {
declaration?: SignatureDeclaration | JSDocSignature;
- typeParameters?: TypeParameter[];
- parameters: Symbol[];
+ typeParameters?: ReadonlyArray;
+ parameters: ReadonlyArray;
}
enum IndexKind {
String = 0,
@@ -2388,14 +2377,14 @@ declare namespace ts {
next?: DiagnosticMessageChain;
}
interface Diagnostic extends DiagnosticRelatedInformation {
- category: DiagnosticCategory;
/** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
reportsUnnecessary?: {};
- code: number;
source?: string;
relatedInformation?: DiagnosticRelatedInformation[];
}
interface DiagnosticRelatedInformation {
+ category: DiagnosticCategory;
+ code: number;
file: SourceFile | undefined;
start: number | undefined;
length: number | undefined;
@@ -2929,13 +2918,6 @@ declare namespace ts {
directoryExists?(directoryName: string): boolean;
getCurrentDirectory?(): string;
}
- /** @deprecated See comment on SymbolWriter */
- interface SymbolTracker {
- trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
- reportInaccessibleThisError?(): void;
- reportPrivateInBaseOfClassExpression?(propertyName: string): void;
- reportInaccessibleUniqueSymbolError?(): void;
- }
interface TextSpan {
start: number;
length: number;
@@ -3166,7 +3148,8 @@ declare namespace ts {
function isParameterPropertyDeclaration(node: Node): node is ParameterPropertyDeclaration;
function isEmptyBindingPattern(node: BindingName): node is BindingPattern;
function isEmptyBindingElement(node: BindingElement): boolean;
- function getCombinedModifierFlags(node: Node): ModifierFlags;
+ function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration;
+ function getCombinedModifierFlags(node: Declaration): ModifierFlags;
function getCombinedNodeFlags(node: Node): NodeFlags;
/**
* Checks to see if the locale is in the appropriate format,
@@ -3212,15 +3195,8 @@ declare namespace ts {
function unescapeLeadingUnderscores(identifier: __String): string;
function idText(identifier: Identifier): string;
function symbolName(symbol: Symbol): string;
- /**
- * Remove extra underscore from escaped identifier text content.
- * @deprecated Use `id.text` for the unescaped text.
- * @param identifier The escaped identifier text.
- * @returns The unescaped identifier text.
- */
- function unescapeIdentifier(id: string): string;
function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined;
- function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName;
+ function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined;
/**
* Gets the JSDoc parameter tags for the node if present.
*
@@ -3655,7 +3631,7 @@ declare namespace ts {
/** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
function createFileLevelUniqueName(text: string): Identifier;
/** Create a unique name generated for a node. */
- function getGeneratedNameForNode(node: Node): Identifier;
+ function getGeneratedNameForNode(node: Node | undefined): Identifier;
function createToken(token: TKind): Token;
function createSuper(): SuperExpression;
function createThis(): ThisExpression & Token;
@@ -3710,7 +3686,11 @@ declare namespace ts {
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode;
- function updateTypleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode;
+ function updateTupleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode;
+ function createOptionalTypeNode(type: TypeNode): OptionalTypeNode;
+ function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode;
+ function createRestTypeNode(type: TypeNode): RestTypeNode;
+ function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode;
function createUnionTypeNode(types: ReadonlyArray): UnionTypeNode;
function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode;
function createIntersectionTypeNode(types: ReadonlyArray): IntersectionTypeNode;
@@ -3763,7 +3743,7 @@ declare namespace ts {
function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression;
function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression;
function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction;
- function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction;
+ /** @deprecated */ function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction;
function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction;
function createDelete(expression: Expression): DeleteExpression;
function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression;
@@ -3781,7 +3761,7 @@ declare namespace ts {
function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression;
function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression;
- function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
+ /** @deprecated */ function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token