- return parent_23.parent.parent;
+ return parent.parent.parent;
}
break;
// The context token is the closing } or " of an attribute, which means
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
case 9 /* StringLiteral */:
- if (parent_23 && ((parent_23.kind === 261 /* JsxAttribute */) || (parent_23.kind === 263 /* JsxSpreadAttribute */))) {
+ if (parent && ((parent.kind === 261 /* JsxAttribute */) || (parent.kind === 263 /* JsxSpreadAttribute */))) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
// properties: NodeArray
- return parent_23.parent.parent;
+ return parent.parent.parent;
}
break;
case 18 /* CloseBraceToken */:
- if (parent_23 &&
- parent_23.kind === 264 /* JsxExpression */ &&
- parent_23.parent && parent_23.parent.kind === 261 /* JsxAttribute */) {
+ if (parent &&
+ parent.kind === 264 /* JsxExpression */ &&
+ parent.parent && parent.parent.kind === 261 /* JsxAttribute */) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
// properties: NodeArray
// each JsxAttribute can have initializer as JsxExpression
- return parent_23.parent.parent.parent;
+ return parent.parent.parent.parent;
}
- if (parent_23 && parent_23.kind === 263 /* JsxSpreadAttribute */) {
+ if (parent && parent.kind === 263 /* JsxSpreadAttribute */) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
// properties: NodeArray
- return parent_23.parent.parent;
+ return parent.parent.parent;
}
break;
}
@@ -87454,8 +89015,8 @@ var ts;
// TODO: Account for computed property name
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
- var name_62 = ts.getNameOfDeclaration(m);
- existingName = ts.isPropertyNameLiteral(name_62) ? ts.getEscapedTextOfIdentifierOrLiteral(name_62) : undefined;
+ var name = ts.getNameOfDeclaration(m);
+ existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
existingMemberNames.set(existingName, true);
}
@@ -87670,7 +89231,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 294 /* SyntaxList */:
+ case 298 /* 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);
@@ -87707,6 +89268,9 @@ var ts;
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
switch (triggerCharacter) {
+ case ".":
+ case "@":
+ return true;
case '"':
case "'":
case "`":
@@ -87715,8 +89279,12 @@ var ts;
case "<":
// Opening JSX tag
return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */;
+ case "/":
+ return ts.isStringLiteralLike(contextToken)
+ ? !!ts.tryGetImportFromModuleSpecifier(contextToken)
+ : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent);
default:
- return ts.Debug.fail(triggerCharacter);
+ return ts.Debug.assertNever(triggerCharacter);
}
}
function isStringLiteralOrTemplate(node) {
@@ -87811,6 +89379,10 @@ var ts;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]);
+ case 121 /* AwaitKeyword */:
+ return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
+ case 120 /* AsyncKeyword */:
+ return highlightSpans(getAsyncAndAwaitOccurrences(node));
default:
return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
? highlightSpans(getModifierOccurrences(node.kind, node.parent))
@@ -87851,16 +89423,16 @@ var ts;
function getThrowStatementOwner(throwStatement) {
var child = throwStatement;
while (child.parent) {
- var parent_24 = child.parent;
- if (ts.isFunctionBlock(parent_24) || parent_24.kind === 273 /* SourceFile */) {
- return parent_24;
+ var parent = child.parent;
+ if (ts.isFunctionBlock(parent) || parent.kind === 273 /* SourceFile */) {
+ return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
// a catch clause, and if the throw-statement occurs within the try block.
- if (ts.isTryStatement(parent_24) && parent_24.tryBlock === child && parent_24.catchClause) {
+ if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
return child;
}
- child = parent_24;
+ child = parent;
}
return undefined;
}
@@ -88058,6 +89630,29 @@ var ts;
});
return keywords;
}
+ function getAsyncAndAwaitOccurrences(node) {
+ var func = ts.getContainingFunction(node);
+ if (!func) {
+ return undefined;
+ }
+ var keywords = [];
+ if (func.modifiers) {
+ func.modifiers.forEach(function (modifier) {
+ pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */);
+ });
+ }
+ ts.forEachChild(func, aggregate);
+ return keywords;
+ function aggregate(node) {
+ if (ts.isAwaitExpression(node)) {
+ pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */);
+ }
+ // Do not cross function boundaries.
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
+ ts.forEachChild(node, aggregate);
+ }
+ }
+ }
function getIfElseOccurrences(ifStatement, sourceFile) {
var keywords = getIfElseKeywords(ifStatement, sourceFile);
var result = [];
@@ -88178,9 +89773,10 @@ var ts;
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
+ var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target;
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
- var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind);
+ var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
entry = {
sourceFile: sourceFile,
languageServiceRefCount: 1,
@@ -88297,11 +89893,11 @@ var ts;
switch (direct.kind) {
case 186 /* CallExpression */:
if (!isAvailableThroughGlobal) {
- var parent_25 = direct.parent;
- if (exportKind === 2 /* ExportEquals */ && parent_25.kind === 231 /* VariableDeclaration */) {
- var name_63 = parent_25.name;
- if (name_63.kind === 71 /* Identifier */) {
- directImports.push(name_63);
+ var parent = direct.parent;
+ if (exportKind === 2 /* ExportEquals */ && parent.kind === 231 /* VariableDeclaration */) {
+ var name = parent.name;
+ if (name.kind === 71 /* Identifier */) {
+ directImports.push(name);
break;
}
}
@@ -88309,6 +89905,8 @@ var ts;
addIndirectUser(direct.getSourceFile());
}
break;
+ case 71 /* Identifier */: // for 'const x = require("y");
+ break; // TODO: GH#23879
case 242 /* ImportEqualsDeclaration */:
handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */));
break;
@@ -88338,6 +89936,11 @@ var ts;
directImports.push(direct);
}
break;
+ case 178 /* ImportType */:
+ directImports.push(direct);
+ break;
+ default:
+ ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct));
}
}
}
@@ -88415,6 +90018,14 @@ var ts;
return;
}
if (decl.kind === 178 /* ImportType */) {
+ if (decl.qualifier) {
+ if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) {
+ singleReferences.push(decl.qualifier);
+ }
+ }
+ else if (exportKind === 2 /* ExportEquals */) {
+ singleReferences.push(decl.argument.literal);
+ }
return;
}
// Ignore if there's a grammar error
@@ -88439,12 +90050,12 @@ var ts;
}
else {
// `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals
- var name_64 = importClause.name;
+ var name = importClause.name;
// If a default import has the same name as the default export, allow to rename it.
// Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
- if (name_64 && (!isForRename || name_64.escapedText === symbolName(exportSymbol))) {
- var defaultImportAlias = checker.getSymbolAtLocation(name_64);
- addSearch(name_64, defaultImportAlias);
+ if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
+ var defaultImportAlias = checker.getSymbolAtLocation(name);
+ addSearch(name, defaultImportAlias);
}
// 'default' might be accessed as a named import `{ default as foo }`.
if (exportKind === 1 /* Default */) {
@@ -88469,8 +90080,8 @@ var ts;
}
for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
var element = _a[_i];
- var name_65 = element.name, propertyName = element.propertyName;
- if (!isNameMatch((propertyName || name_65).escapedText)) {
+ var name = element.name, propertyName = element.propertyName;
+ if (!isNameMatch((propertyName || name).escapedText)) {
continue;
}
if (propertyName) {
@@ -88478,16 +90089,16 @@ var ts;
singleReferences.push(propertyName);
// If renaming `{ foo as bar }`, don't touch `bar`, just `foo`.
// But do rename `foo` in ` { default as foo }` if that's the original export name.
- if (!isForRename || name_65.escapedText === exportSymbol.escapedName) {
+ if (!isForRename || name.escapedText === exportSymbol.escapedName) {
// Search locally for `bar`.
- addSearch(name_65, checker.getSymbolAtLocation(name_65));
+ addSearch(name, checker.getSymbolAtLocation(name));
}
}
else {
var localSymbol = element.kind === 251 /* ExportSpecifier */ && element.propertyName
? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
- : checker.getSymbolAtLocation(name_65);
- addSearch(name_65, localSymbol);
+ : checker.getSymbolAtLocation(name);
+ addSearch(name, localSymbol);
}
}
}
@@ -88500,24 +90111,18 @@ var ts;
function findNamespaceReExports(sourceFileLike, name, checker) {
var namespaceImportSymbol = checker.getSymbolAtLocation(name);
return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
- if (statement.kind !== 249 /* ExportDeclaration */)
+ if (!ts.isExportDeclaration(statement))
return;
- var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier;
- if (moduleSpecifier || !exportClause)
- return;
- for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) {
- var element = _b[_i];
- if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) {
- return true;
- }
- }
+ var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
+ return !moduleSpecifier && exportClause &&
+ exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
});
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var referencingFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var referencingFile = sourceFiles_5[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === 273 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
@@ -88547,8 +90152,8 @@ var ts;
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
var map = ts.createMap();
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
@@ -88653,6 +90258,9 @@ var ts;
else if (ts.isBinaryExpression(parent.parent)) {
return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true);
}
+ else if (ts.isJSDocTypedefTag(parent)) {
+ return exportInfo(symbol, 0 /* Named */);
+ }
}
function getExportAssignmentExport(ex) {
// Get the symbol for the `export =` node; its parent is the module it's the export of.
@@ -88697,7 +90305,7 @@ var ts;
// If the import has a different name than the export, do not continue searching.
// If `importedName` is undefined, do continue searching as the export is anonymous.
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
- var importedName = symbolName(importedSymbol);
+ var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
}
@@ -88764,15 +90372,6 @@ var ts;
return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
}
FindAllReferences.getExportInfo = getExportInfo;
- function symbolName(symbol) {
- if (symbol.escapedName !== "default" /* Default */) {
- return symbol.escapedName;
- }
- return ts.forEach(symbol.declarations, function (decl) {
- var name = ts.getNameOfDeclaration(decl);
- return name && name.kind === 71 /* Identifier */ && name.escapedText;
- });
- }
/** If at an export specifier, go to the symbol it refers to. */
function skipExportSpecifierSymbol(symbol, checker) {
// For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
@@ -88847,9 +90446,9 @@ var ts;
// 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 === 270 /* ShorthandPropertyAssignment */) {
- var result_4 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); });
- return result_4;
+ var result_5 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); });
+ return result_5;
}
else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -88882,8 +90481,8 @@ var ts;
case "symbol": {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_66 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_66, kind: kind_1, displayParts: displayParts_1 };
+ var name_3 = displayParts_1.map(function (p) { return p.text; }).join("");
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 };
}
case "label": {
var node_3 = def.node;
@@ -88891,13 +90490,13 @@ var ts;
}
case "keyword": {
var node_4 = def.node;
- var name_67 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_67, kind: "keyword" /* keyword */, displayParts: [{ text: name_67, kind: "keyword" /* keyword */ }] };
+ var name_4 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] };
}
case "this": {
var node_5 = def.node;
var symbol = checker.getSymbolAtLocation(node_5);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case "string": {
@@ -89010,7 +90609,7 @@ var ts;
if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
if (ts.isSourceFile(node)) {
var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
- return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet);
+ return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
}
if (!options.implementations) {
var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
@@ -89025,32 +90624,36 @@ var ts;
// String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
}
- if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) {
- return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet);
+ var moduleReferences = ts.emptyArray;
+ var moduleSourceFile = isModuleSymbol(symbol);
+ if (moduleSourceFile) {
+ var exportEquals = symbol.exports.get("export=" /* ExportEquals */);
+ // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
+ moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
+ if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
+ return moduleReferences;
+ // Continue to get references to 'export ='.
+ symbol = ts.skipAlias(exportEquals, checker);
+ node = undefined;
}
- return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
+ return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
}
Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
- function isModuleReferenceLocation(node) {
- if (!ts.isStringLiteralLike(node)) {
- return false;
- }
- switch (node.parent.kind) {
- case 238 /* ModuleDeclaration */:
- case 253 /* ExternalModuleReference */:
- case 243 /* ImportDeclaration */:
- case 249 /* ExportDeclaration */:
- return true;
- case 186 /* CallExpression */:
- return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent);
- default:
- return false;
- }
+ function isModuleSymbol(symbol) {
+ return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile);
}
- function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) {
+ function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
ts.Debug.assert(!!symbol.valueDeclaration);
- var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) {
+ var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) {
if (reference.kind === "import") {
+ var parent = reference.literal.parent;
+ if (ts.isLiteralTypeNode(parent)) {
+ var importType = ts.cast(parent.parent, ts.isImportTypeNode);
+ if (excludeImportTypeOfExportEquals && !importType.qualifier) {
+ return undefined;
+ }
+ }
+ // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway.
return { type: "node", node: reference.literal };
}
else {
@@ -89073,10 +90676,11 @@ var ts;
}
break;
default:
+ // This may be merged with something.
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return [{ definition: { type: "symbol", symbol: symbol }, references: references }];
+ return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray;
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
@@ -89104,17 +90708,17 @@ var ts;
}
/** Core find-all-references algorithm for a normal symbol. */
function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
- symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
+ symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
// Compute the meaning from the location and the symbol it references
- var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
+ var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
var result = [];
- var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
- if (node.kind === 79 /* DefaultKeyword */) {
+ var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
+ if (node && node.kind === 79 /* DefaultKeyword */) {
addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
else {
- var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) });
+ var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] });
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
@@ -89160,7 +90764,6 @@ var ts;
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
- ts.Debug.assert(decl.kind === 273 /* SourceFile */);
ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol));
}
return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
@@ -89234,7 +90837,7 @@ var ts;
// here appears to be intentional).
var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b;
var escapedText = ts.escapeLeadingUnderscores(text);
- var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
+ var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } };
};
/**
@@ -89278,10 +90881,8 @@ var ts;
var addRef = state.referenceAdder(exportSymbol);
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
- // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
+ if (shouldAddSingleReference(singleRef, state))
addRef(singleRef);
- }
}
}
// For each import, find all references to that import in its source file.
@@ -89310,6 +90911,17 @@ var ts;
}
}
}
+ function shouldAddSingleReference(singleRef, state) {
+ if (!hasMatchingMeaning(singleRef, state))
+ return false;
+ if (!state.options.isForRename)
+ return true;
+ // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;`
+ if (!ts.isIdentifier(singleRef))
+ return false;
+ // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
+ return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
+ }
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol, state) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -89333,22 +90945,14 @@ var ts;
var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */);
if (bindingElement &&
bindingElement.parent.kind === 179 /* ObjectBindingPattern */ &&
+ ts.isIdentifier(bindingElement.name) &&
!bindingElement.propertyName) {
return bindingElement;
}
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
var bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
- if (!bindingElement)
- return undefined;
- var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
- var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
- if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
- // See GH#16922
- ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
- return propSymbol.target;
- }
- return propSymbol;
+ return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement);
}
/**
* Determines the smallest scope in which a symbol may have named references.
@@ -89519,6 +91123,9 @@ var ts;
getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
}
}
+ function hasMatchingMeaning(referenceLocation, state) {
+ return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
+ }
function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
@@ -89534,9 +91141,8 @@ var ts;
}
return;
}
- if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
+ if (!hasMatchingMeaning(referenceLocation, state))
return;
- }
var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
if (!referenceSymbol) {
return;
@@ -90197,7 +91803,9 @@ var ts;
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.
- return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; })
+ return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) ||
+ // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias
+ symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })
? [sigInfo]
: [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node));
}
@@ -90252,14 +91860,14 @@ var ts;
function getReferenceAtPosition(sourceFile, position, program) {
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
if (referencePath) {
- var file = ts.tryResolveScriptReference(program, sourceFile, referencePath);
- return file && { fileName: referencePath.fileName, file: file };
+ var file_16 = ts.tryResolveScriptReference(program, sourceFile, referencePath);
+ return file_16 && { fileName: referencePath.fileName, file: file_16 };
}
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
- var file = reference && program.getSourceFile(reference.resolvedFileName);
- return file && { fileName: typeReferenceDirective.fileName, file: file };
+ var file_17 = reference && program.getSourceFile(reference.resolvedFileName);
+ return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 };
}
return undefined;
}
@@ -90431,6 +92039,7 @@ var ts;
"author",
"argument",
"borrows",
+ "callback",
"class",
"constant",
"constructor",
@@ -90495,10 +92104,12 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 293 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
+ case 297 /* JSDocPropertyTag */:
return [declaration];
- case 292 /* JSDocTypedefTag */:
- return [declaration.parent];
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
}
@@ -90518,17 +92129,18 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 286 /* JSDocAugmentsTag */:
+ case 289 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 290 /* JSDocTypeTag */:
+ case 294 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 292 /* JSDocTypedefTag */:
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */:
- var name_68 = tag.name;
- return name_68 ? withNode(name_68) : comment;
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ case 297 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
+ var name = tag.name;
+ return name ? withNode(name) : comment;
default:
return comment;
}
@@ -90851,12 +92463,42 @@ var ts;
JsTyping.isTypingUpToDate = isTypingUpToDate;
/* @internal */
JsTyping.nodeCoreModuleList = [
- "buffer", "querystring", "events", "http", "cluster",
- "zlib", "os", "https", "punycode", "repl", "readline",
- "vm", "child_process", "url", "dns", "net",
- "dgram", "fs", "path", "string_decoder", "tls",
- "crypto", "stream", "util", "assert", "tty", "domain",
- "constants", "process", "v8", "timers", "console"
+ "assert",
+ "async_hooks",
+ "buffer",
+ "child_process",
+ "cluster",
+ "console",
+ "constants",
+ "crypto",
+ "dgram",
+ "dns",
+ "domain",
+ "events",
+ "fs",
+ "http",
+ "https",
+ "http2",
+ "inspector",
+ "net",
+ "os",
+ "path",
+ "perf_hooks",
+ "process",
+ "punycode",
+ "querystring",
+ "readline",
+ "repl",
+ "stream",
+ "string_decoder",
+ "timers",
+ "tls",
+ "tty",
+ "url",
+ "util",
+ "v8",
+ "vm",
+ "zlib"
];
/* @internal */
JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
@@ -90915,8 +92557,8 @@ var ts;
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
- var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
- addInferredTypings(module, "Inferred typings from unresolved imports");
+ var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ addInferredTypings(module_1, "Inferred typings from unresolved imports");
}
// Add the cached typing locations for inferred typings that are already installed
packageNameToTypingLocation.forEach(function (typing, name) {
@@ -91013,8 +92655,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_5.config;
+ var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_6.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
@@ -91114,7 +92756,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_12 = function (sourceFile) {
+ var _loop_14 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) {
return "continue";
@@ -91124,9 +92766,9 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_12(sourceFile);
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var sourceFile = sourceFiles_7[_i];
+ _loop_14(sourceFile);
}
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
@@ -91425,9 +93067,9 @@ var ts;
break;
case 181 /* BindingElement */:
case 231 /* VariableDeclaration */:
- var _d = node, name_69 = _d.name, initializer = _d.initializer;
- if (ts.isBindingPattern(name_69)) {
- addChildrenRecursively(name_69);
+ var _d = node, name = _d.name, initializer = _d.initializer;
+ if (ts.isBindingPattern(name)) {
+ addChildrenRecursively(name);
}
else if (initializer && isFunctionOrClassExpression(initializer)) {
if (initializer.name) {
@@ -91503,7 +93145,7 @@ var ts;
if (ts.hasJSDocNodes(node)) {
ts.forEach(node.jsDoc, function (jsDoc) {
ts.forEach(jsDoc.tags, function (tag) {
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (ts.isJSDocTypeAlias(tag)) {
addLeafNode(tag);
}
});
@@ -91578,6 +93220,7 @@ var ts;
}
/** Merge source into target. Source should be thrown away after this is called. */
function merge(target, source) {
+ var _a;
target.additionalNodes = target.additionalNodes || [];
target.additionalNodes.push(source.node);
if (source.additionalNodes) {
@@ -91588,7 +93231,6 @@ var ts;
mergeChildren(target.children);
sortChildren(target.children);
}
- var _a;
}
/** Recursively ensure that each NavNode's children are in sorted order. */
function sortChildren(children) {
@@ -91616,8 +93258,6 @@ var ts;
case 192 /* ArrowFunction */:
case 204 /* ClassExpression */:
return getFunctionOrClassName(node);
- case 292 /* JSDocTypedefTag */:
- return getJSDocTypedefTagName(node);
default:
return undefined;
}
@@ -91659,29 +93299,10 @@ var ts;
return "()";
case 159 /* IndexSignature */:
return "[]";
- case 292 /* JSDocTypedefTag */:
- return getJSDocTypedefTagName(node);
default:
return "";
}
}
- function getJSDocTypedefTagName(node) {
- if (node.name) {
- return node.name.text;
- }
- else {
- var parentNode = node.parent && node.parent.parent;
- if (parentNode && parentNode.kind === 213 /* VariableStatement */) {
- if (parentNode.declarationList.declarations.length > 0) {
- var nameIdentifier = parentNode.declarationList.declarations[0].name;
- if (nameIdentifier.kind === 71 /* Identifier */) {
- return nameIdentifier.text;
- }
- }
- }
- return "";
- }
- }
/** Flattens the NavNode tree to a list, keeping only the top-level items. */
function topLevelItems(root) {
var topLevel = [];
@@ -91707,7 +93328,8 @@ var ts;
case 238 /* ModuleDeclaration */:
case 273 /* SourceFile */:
case 236 /* TypeAliasDeclaration */:
- case 292 /* JSDocTypedefTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
return true;
case 154 /* Constructor */:
case 153 /* MethodDeclaration */:
@@ -91870,17 +93492,23 @@ var ts;
*/
function organizeImports(sourceFile, formatContext, host, program, _preferences) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
+ var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
// All of the old ImportDeclarations in the file, in syntactic order.
var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
- organizeImportsWorker(topLevelImportDecls);
+ organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
+ // All of the old ExportDeclarations in the file, in syntactic order.
+ var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
+ organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
var ambientModule = _a[_i];
var ambientModuleBody = getModuleBlock(ambientModule);
var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
- organizeImportsWorker(ambientModuleImportDecls);
+ organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
+ var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
+ organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
- function organizeImportsWorker(oldImportDecls) {
+ function organizeImportsWorker(oldImportDecls, coalesce) {
if (ts.length(oldImportDecls) === 0) {
return;
}
@@ -91894,7 +93522,7 @@ var ts;
var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
return getExternalModuleName(importGroup[0].moduleSpecifier)
- ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
+ ? coalesce(importGroup)
: importGroup;
});
// Delete or replace the first import.
@@ -91936,10 +93564,10 @@ var ts;
usedImports.push(importDecl);
continue;
}
- var name_70 = importClause.name, namedBindings = importClause.namedBindings;
+ var name = importClause.name, namedBindings = importClause.namedBindings;
// Default import
- if (name_70 && !isDeclarationUsed(name_70)) {
- name_70 = undefined;
+ if (name && !isDeclarationUsed(name)) {
+ name = undefined;
}
if (namedBindings) {
if (ts.isNamespaceImport(namedBindings)) {
@@ -91958,8 +93586,8 @@ var ts;
}
}
}
- if (name_70 || namedBindings) {
- usedImports.push(updateImportDeclarationAndClause(importDecl, name_70, namedBindings));
+ if (name || namedBindings) {
+ usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
}
}
return usedImports;
@@ -91969,7 +93597,9 @@ var ts;
}
}
function getExternalModuleName(specifier) {
- return ts.isStringLiteralLike(specifier) ? specifier.text : undefined;
+ return specifier !== undefined && ts.isStringLiteralLike(specifier)
+ ? specifier.text
+ : undefined;
}
/* @internal */ // Internal for testing
/**
@@ -92015,15 +93645,14 @@ var ts;
}
}
newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
- var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
- return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
- compareIdentifiers(s1.name, s2.name);
- });
+ var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
var importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
var newNamedImports = sortedImportSpecifiers.length === 0
- ? undefined
+ ? newDefaultImport
+ ? undefined
+ : ts.createNamedImports(ts.emptyArray)
: namedImports.length === 0
? ts.createNamedImports(sortedImportSpecifiers)
: ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers);
@@ -92049,8 +93678,8 @@ var ts;
importWithoutClause = importWithoutClause || importDeclaration;
continue;
}
- var _a = importDeclaration.importClause, name_71 = _a.name, namedBindings = _a.namedBindings;
- if (name_71) {
+ var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ if (name) {
defaultImports.push(importDeclaration);
}
if (namedBindings) {
@@ -92069,23 +93698,77 @@ var ts;
namedImports: namedImports,
};
}
- function compareIdentifiers(s1, s2) {
- return ts.compareStringsCaseSensitive(s1.text, s2.text);
- }
}
OrganizeImports.coalesceImports = coalesceImports;
+ /* @internal */ // Internal for testing
+ /**
+ * @param exportGroup a list of ExportDeclarations, all with the same module name.
+ */
+ function coalesceExports(exportGroup) {
+ if (exportGroup.length === 0) {
+ return exportGroup;
+ }
+ var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
+ var coalescedExports = [];
+ if (exportWithoutClause) {
+ coalescedExports.push(exportWithoutClause);
+ }
+ if (namedExports.length === 0) {
+ return coalescedExports;
+ }
+ var newExportSpecifiers = [];
+ newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
+ var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
+ var exportDecl = namedExports[0];
+ coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
+ return coalescedExports;
+ /*
+ * Returns entire export declarations because they may already have been rewritten and
+ * may lack parent pointers. The desired parts can easily be recovered based on the
+ * categorization.
+ */
+ function getCategorizedExports(exportGroup) {
+ var exportWithoutClause;
+ var namedExports = [];
+ for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
+ var exportDeclaration = exportGroup_1[_i];
+ if (exportDeclaration.exportClause === undefined) {
+ // Only the first such export is interesting - the others are redundant.
+ // Note: Unfortunately, we will lose trivia that was on this node.
+ exportWithoutClause = exportWithoutClause || exportDeclaration;
+ }
+ else {
+ namedExports.push(exportDeclaration);
+ }
+ }
+ return {
+ exportWithoutClause: exportWithoutClause,
+ namedExports: namedExports,
+ };
+ }
+ }
+ OrganizeImports.coalesceExports = coalesceExports;
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
}
+ function sortSpecifiers(specifiers) {
+ return ts.stableSort(specifiers, function (s1, s2) {
+ return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
+ compareIdentifiers(s1.name, s2.name);
+ });
+ }
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
var name2 = getExternalModuleName(m2);
return ts.compareBooleans(name1 === undefined, name2 === undefined) ||
ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) ||
- ts.compareStringsCaseSensitive(name1, name2);
+ ts.compareStringsCaseInsensitive(name1, name2);
}
OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
+ function compareIdentifiers(s1, s2) {
+ return ts.compareStringsCaseInsensitive(s1.text, s2.text);
+ }
})(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
})(ts || (ts = {}));
/* @internal */
@@ -92095,7 +93778,7 @@ var ts;
var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
- for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate;
var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
@@ -92107,25 +93790,16 @@ var ts;
}
ts.getEditsForFileRename = getEditsForFileRename;
function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) {
- var cfg = program.getCompilerOptions().configFile;
- if (!cfg)
- return;
- var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath);
+ var configFile = program.getCompilerOptions().configFile;
+ var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath);
if (oldFile) {
- changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath);
+ changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath);
}
}
- function getFilesEntry(cfg, fileName) {
- var filesProp = ts.find(cfg.properties, function (prop) {
- return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
- });
- var files = filesProp && filesProp.initializer;
- return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined;
- }
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
- function getImportsToUpdate(program, oldFilePath) {
+ function getImportsToUpdate(program, oldFilePath, host) {
var checker = program.getTypeChecker();
var result = [];
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
@@ -92141,8 +93815,10 @@ var ts;
// If it resolved to something already, ignore.
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
- var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
- if (ts.contains(resolved.failedLookupLocations, oldFilePath)) {
+ var resolved = host.resolveModuleNames
+ ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
+ : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
+ if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
}
@@ -92151,11 +93827,11 @@ var ts;
}
function getPathUpdater(oldFilePath, newFilePath, host) {
// Get the relative path from old to new location, and append it on to the end of imports and normalize.
- var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
+ var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
return function (oldPath) {
if (!ts.pathIsRelative(oldPath))
return;
- return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
+ return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
};
}
function createStringRange(node, sourceFile) {
@@ -92176,7 +93852,27 @@ var ts;
OutliningElementsCollector.collectElements = collectElements;
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
var depthRemaining = 40;
- sourceFile.forEachChild(function walk(n) {
+ var current = 0;
+ var statements = sourceFile.statements;
+ var n = statements.length;
+ while (current < n) {
+ while (current < n && !ts.isAnyImportSyntax(statements[current])) {
+ visitNonImportNode(statements[current]);
+ current++;
+ }
+ if (current === n)
+ break;
+ var firstImport = current;
+ while (current < n && ts.isAnyImportSyntax(statements[current])) {
+ addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
+ current++;
+ }
+ var lastImport = current - 1;
+ if (lastImport !== firstImport) {
+ out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
+ }
+ }
+ function visitNonImportNode(n) {
if (depthRemaining === 0)
return;
cancellationToken.throwIfCancellationRequested();
@@ -92189,17 +93885,17 @@ var ts;
depthRemaining--;
if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
// Consider an 'else if' to be on the same depth as the 'if'.
- walk(n.expression);
- walk(n.thenStatement);
+ visitNonImportNode(n.expression);
+ visitNonImportNode(n.thenStatement);
depthRemaining++;
- walk(n.elseStatement);
+ visitNonImportNode(n.elseStatement);
depthRemaining--;
}
else {
- n.forEachChild(walk);
+ n.forEachChild(visitNonImportNode);
}
depthRemaining++;
- });
+ }
}
function addRegionOutliningSpans(sourceFile, out) {
var regions = [];
@@ -92214,7 +93910,7 @@ var ts;
}
if (!result[1]) {
var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region"));
+ regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -92248,7 +93944,7 @@ var ts;
break;
case 3 /* MultiLineCommentTrivia */:
combineAndAddMultipleSingleLineComments();
- out.push(createOutliningSpanFromBounds(pos, end));
+ out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
singleLineCommentCount = 0;
break;
default:
@@ -92259,12 +93955,12 @@ var ts;
function combineAndAddMultipleSingleLineComments() {
// Only outline spans of two or more consecutive single line comments
if (singleLineCommentCount > 1) {
- out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd));
+ out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
}
}
}
- function createOutliningSpanFromBounds(pos, end) {
- return createOutliningSpan(ts.createTextSpanFromBounds(pos, end));
+ function createOutliningSpanFromBounds(pos, end, kind) {
+ return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
switch (n.kind) {
@@ -92298,7 +93994,7 @@ var ts;
default:
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
- return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile));
+ return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
}
case 239 /* ModuleBlock */:
return spanForNode(n.parent);
@@ -92330,14 +94026,14 @@ var ts;
return undefined;
}
var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
- return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
+ return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
}
- function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) {
+ function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
if (hintSpan === void 0) { hintSpan = textSpan; }
if (autoCollapse === void 0) { autoCollapse = false; }
if (bannerText === void 0) { bannerText = "..."; }
- return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
+ return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
}
})(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
})(ts || (ts = {}));
@@ -92620,13 +94316,13 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_13 = function (start) {
+ var _loop_15 = function (start) {
if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
return { value: start };
}
};
for (var start = 0; start <= n; start++) {
- var state_4 = _loop_13(start);
+ var state_4 = _loop_15(start);
if (typeof state_4 === "object")
return state_4.value;
}
@@ -93172,6 +94868,9 @@ var ts;
if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
return undefined;
}
+ // Can't rename a module name.
+ if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node))
+ return undefined;
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
@@ -93291,7 +94990,7 @@ var ts;
var nameToDeclarations = sourceFile.getNamedDeclarations();
var declarations = nameToDeclarations.get(name.text);
if (declarations) {
- var _loop_14 = function (declaration) {
+ var _loop_16 = function (declaration) {
var symbol = declaration.symbol;
if (symbol) {
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
@@ -93305,7 +95004,7 @@ var ts;
};
for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) {
var declaration = declarations_12[_b];
- var state_5 = _loop_14(declaration);
+ var state_5 = _loop_16(declaration);
if (typeof state_5 === "object")
return state_5.value;
}
@@ -93652,7 +95351,9 @@ var ts;
program.getSemanticDiagnostics(sourceFile);
var checker = program.getDiagnosticsProducingTypeChecker();
var diags = [];
- if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))) {
+ if (sourceFile.commonJsModuleIndicator &&
+ (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
+ containsTopLevelCommonjs(sourceFile)) {
diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
}
var isJsFile = ts.isSourceFileJavaScript(sourceFile);
@@ -93691,19 +95392,42 @@ var ts;
for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) {
var moduleSpecifier = _c[_b];
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
- var name_72 = importNameForConvertToDefaultImport(importNode);
- if (!name_72)
+ var name = importNameForConvertToDefaultImport(importNode);
+ if (!name)
continue;
- var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
- diags.push(ts.createDiagnosticForNode(name_72, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
+ diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
}
}
- return diags.concat(checker.getSuggestionDiagnostics(sourceFile));
+ return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; });
}
ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
+ // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
+ function containsTopLevelCommonjs(sourceFile) {
+ return sourceFile.statements.some(function (statement) {
+ switch (statement.kind) {
+ case 213 /* VariableStatement */:
+ return statement.declarationList.declarations.some(function (decl) {
+ return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
+ });
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ if (!ts.isBinaryExpression(expression))
+ return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
+ var kind = ts.getSpecialPropertyAssignmentKind(expression);
+ return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
+ }
+ default:
+ return false;
+ }
+ });
+ }
+ function propertyAccessLeftHandSide(node) {
+ return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
+ }
function importNameForConvertToDefaultImport(node) {
switch (node.kind) {
case 243 /* ImportDeclaration */:
@@ -94320,9 +96044,9 @@ var ts;
return false;
}
// If the parent is not sourceFile or module block it is local variable
- for (var parent_26 = declaration.parent; !ts.isFunctionBlock(parent_26); parent_26 = parent_26.parent) {
+ for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent_26.kind === 273 /* SourceFile */ || parent_26.kind === 239 /* ModuleBlock */) {
+ if (parent.kind === 273 /* SourceFile */ || parent.kind === 239 /* ModuleBlock */) {
return false;
}
}
@@ -94434,7 +96158,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_15 = function (opt) {
+ var _loop_17 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -94453,7 +96177,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_15(opt);
+ _loop_17(opt);
}
return options;
}
@@ -94857,6 +96581,7 @@ var ts;
rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
+ rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */),
// Special handling of unary operators.
// Prefix operators generally shouldn't have a space between
// them and their target unary expression.
@@ -95317,6 +97042,9 @@ var ts;
function isArrowFunctionContext(context) {
return context.contextNode.kind === 192 /* ArrowFunction */;
}
+ function isImportTypeContext(context) {
+ return context.contextNode.kind === 178 /* ImportType */;
+ }
function isNonJsxSameLineTokenContext(context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}
@@ -95439,18 +97167,18 @@ var ts;
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(map.length);
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
- var rule = rules_1[_i];
- var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
- for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
+ var rule_1 = rules_1[_i];
+ var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific;
+ for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) {
var left = _b[_a];
- for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) {
var right = _d[_c];
var index = getRuleBucketIndex(left, right);
var rulesBucket = map[index];
if (rulesBucket === undefined) {
rulesBucket = map[index] = [];
}
- addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
+ addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index);
}
}
}
@@ -96757,7 +98485,7 @@ var ts;
NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
})(NextTokenKind || (NextTokenKind = {}));
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
- var nextToken = ts.findNextToken(precedingToken, current);
+ var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
if (!nextToken) {
return 0 /* Unknown */;
}
@@ -96806,9 +98534,10 @@ var ts;
}
function getContainingList(node, sourceFile) {
if (node.parent) {
+ var end = node.end;
switch (node.parent.kind) {
case 161 /* TypeReference */:
- return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
case 183 /* ObjectLiteralExpression */:
return node.parent.properties;
case 182 /* ArrayLiteralExpression */:
@@ -96823,22 +98552,25 @@ var ts;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.parameters, start, end);
}
case 234 /* ClassDeclaration */:
- return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end);
case 187 /* NewExpression */:
case 186 /* CallExpression */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.arguments, start, end);
}
case 232 /* VariableDeclarationList */:
- return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
case 246 /* NamedImports */:
case 250 /* NamedExports */:
- return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
}
}
return undefined;
@@ -97160,10 +98892,10 @@ var ts;
return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getAdjustedEndPosition(sourceFile, node, options) {
+ var end = node.end;
if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
- return node.getEnd();
+ return end;
}
- var end = node.getEnd();
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
? newEnd
@@ -97188,7 +98920,8 @@ var ts;
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
this.changes = [];
- this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
+ 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
}
ChangeTracker.fromContext = function (context) {
@@ -97232,35 +98965,14 @@ var ts;
this.deleteNode(sourceFile, node);
return this;
}
- var id = ts.getNodeId(node);
- ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice");
- this.deletedNodesInLists[id] = true;
- if (index !== containingList.length - 1) {
- var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false);
- if (nextToken && isSeparator(node, nextToken)) {
- // find first non-whitespace position in the leading trivia of the node
- var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- var nextElement = containingList[index + 1];
- /// find first non-whitespace position in the leading trivia of the next node
- var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node
- this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- }
- }
- else {
- var prev = containingList[index - 1];
- if (this.deletedNodesInLists[ts.getNodeId(prev)]) {
- var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- var end = getAdjustedEndPosition(sourceFile, node, {});
- this.deleteRange(sourceFile, { pos: pos, end: end });
- }
- else {
- var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false);
- if (previousToken && isSeparator(node, previousToken)) {
- this.deleteNodeRange(sourceFile, previousToken, node);
- }
- }
- }
+ // 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) {
@@ -97289,10 +99001,13 @@ var ts;
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
+ ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
+ var next = ts.findNextToken(node, node.parent, sourceFile);
+ return next && next.kind === 26 /* CommaToken */ ? next : undefined;
+ };
ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
- return this.replaceNode(sourceFile, oldNode, newNode, {
- suffix: "," + this.newLineCharacter
- });
+ var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
+ return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
@@ -97326,7 +99041,8 @@ var ts;
// 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 text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter;
+ var indent = sourceFile.text.slice(lineStartPosition, startPosition);
+ var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
this.insertText(sourceFile, token.getStart(sourceFile), text);
};
ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
@@ -97399,20 +99115,38 @@ var ts;
};
ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
var clsStart = cls.getStart(sourceFile);
- var prefix = "";
- var suffix = this.newLineCharacter;
- if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
- prefix = this.newLineCharacter;
- // For `class C {\n}`, don't add the trailing "\n"
- if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any'
- suffix = "";
- }
- }
var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
+ this.formatContext.options.indentSize;
- this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix });
+ this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls)));
+ };
+ ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) {
+ if (cls.members.length === 0) {
+ if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
+ // For `class C {\n}`, don't add the trailing "\n"
+ var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any'
+ return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" };
+ }
+ else {
+ return { prefix: "", suffix: this.newLineCharacter };
+ }
+ }
+ else {
+ return { prefix: this.newLineCharacter, suffix: "" };
+ }
+ };
+ ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
};
ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ 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));
+ };
+ ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
if (needSemicolonBetween(after, newNode)) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
@@ -97421,9 +99155,13 @@ var ts;
}
}
var endPosition = getAdjustedEndPosition(sourceFile, after, {});
- return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after));
+ return endPosition;
};
- ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) {
+ ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
+ var options = this.getInsertNodeAfterOptionsWorker(after);
+ 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 };
}
@@ -97468,13 +99206,16 @@ var ts;
this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
}
};
+ ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
+ this.insertText(sourceFile, node.getStart(sourceFile), "export ");
+ };
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
* i.e. arguments in arguments lists, parameters in parameter lists etc.
* Note that separators are part of the node in statements and class elements.
*/
- ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
- var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
+ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
+ if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
return this;
@@ -97592,6 +99333,19 @@ var ts;
}
});
};
+ ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () {
+ var _this = this;
+ this.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);
+ if (lastNonDeletedIndex !== -1) {
+ _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
+ }
+ });
+ };
/**
* Note: after calling this, the TextChanges object must be discarded!
* @param validate only for tests
@@ -97600,11 +99354,24 @@ var ts;
*/
ChangeTracker.prototype.getChanges = function (validate) {
this.finishClassesWithNodesInsertedAtStart();
- return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ 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;
+ changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter));
+ }
+ return changes;
+ };
+ ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
+ this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
};
return ChangeTracker;
}());
textChanges_3.ChangeTracker = ChangeTracker;
+ // find first non-whitespace position in the leading trivia of the node
+ function startPositionToDeleteNodeInList(sourceFile, node) {
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ }
function getClassBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end];
}
@@ -97614,15 +99381,16 @@ var ts;
return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
var sourceFile = changesInFile[0].sourceFile;
// order changes by start position
- var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
- var _loop_16 = function (i) {
+ // 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_18 = 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_16(i);
+ _loop_18(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -97631,6 +99399,11 @@ var ts;
});
}
changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function newFileChanges(oldFile, fileName, statements, newLineCharacter) {
+ var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
+ return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true };
+ }
+ changesToText.newFileChanges = newFileChanges;
function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
if (change.kind === ChangeKind.Remove) {
return "";
@@ -97980,10 +99753,11 @@ var ts;
}
refactor_1.getEditsForRefactor = getEditsForRefactor;
})(refactor = ts.refactor || (ts.refactor = {}));
- function getRefactorContextLength(context) {
- return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition;
+ function getRefactorContextSpan(_a) {
+ var startPosition = _a.startPosition, endPosition = _a.endPosition;
+ return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
}
- ts.getRefactorContextLength = getRefactorContextLength;
+ ts.getRefactorContextSpan = getRefactorContextSpan;
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -98051,7 +99825,7 @@ var ts;
if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
if (!decl.typeParameters) {
var typeParameters = ts.getJSDocTypeParameterDeclarations(decl);
- if (typeParameters)
+ if (typeParameters.length)
changes.insertTypeParameters(sourceFile, decl, typeParameters);
}
var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile);
@@ -98087,18 +99861,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 161 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -98122,7 +99896,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
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);
@@ -98403,7 +100177,7 @@ var ts;
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
switch (importNode.kind) {
case 242 /* ImportEqualsDeclaration */:
- changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
+ changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
break;
case 186 /* CallExpression */:
if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
@@ -98450,8 +100224,8 @@ var ts;
function forEachExportReference(sourceFile, cb) {
sourceFile.forEachChild(function recur(node) {
if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
- var parent_27 = node.parent;
- cb(node, ts.isBinaryExpression(parent_27) && parent_27.left === node && parent_27.operatorToken.kind === 58 /* EqualsToken */);
+ var parent = node.parent;
+ cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
}
node.forEachChild(recur);
});
@@ -98467,7 +100241,7 @@ var ts;
case 186 /* CallExpression */: {
if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
// For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
+ changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
}
return false;
}
@@ -98540,27 +100314,30 @@ var ts;
changes.deleteNode(sourceFile, assignment.parent);
}
else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
+ : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
+ : undefined;
+ if (replacement) {
+ changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
+ return replacement[1];
+ }
+ else {
+ changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default");
+ return true;
}
- changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
- return changedToDefaultExport;
}
}
else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
convertNamedExport(sourceFile, assignment, changes, exports);
}
return false;
- var _a;
}
/**
* Convert `module.exports = { ... }` to individual exports..
* We can't always do this if the module has interesting members -- then it will be a default export instead.
*/
function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
+ var statements = ts.mapAllOrFail(object.properties, function (prop) {
switch (prop.kind) {
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
@@ -98576,6 +100353,7 @@ var ts;
ts.Debug.assertNever(prop);
}
});
+ return statements && [statements, false];
}
function convertNamedExport(sourceFile, assignment, changes, exports) {
// If "originalKeywordKind" was set, this is e.g. `exports.
@@ -98596,30 +100374,6 @@ var ts;
convertExportsPropertyAssignment(assignment, sourceFile, changes);
}
}
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 191 /* FunctionExpression */:
- case 192 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 204 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 186 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
function convertReExportAll(reExported, checker) {
// `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
var moduleSpecifier = reExported.text;
@@ -98695,7 +100449,7 @@ var ts;
: makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
});
if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
}
}
// falls through -- object destructuring has an interesting pattern and must be a variable declaration
@@ -98706,7 +100460,7 @@ var ts;
*/
var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
];
}
@@ -98732,16 +100486,16 @@ var ts;
// This was a use of a different symbol with the same name, due to shadowing. Ignore.
continue;
}
- var parent_28 = use.parent;
- if (ts.isPropertyAccessExpression(parent_28)) {
- var expression = parent_28.expression, propertyName = parent_28.name.text;
+ var parent = use.parent;
+ if (ts.isPropertyAccessExpression(parent)) {
+ var expression = parent.expression, propertyName = parent.name.text;
ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers`
var idName = namedBindingsNames.get(propertyName);
if (idName === undefined) {
idName = makeUniqueName(propertyName, identifiers);
namedBindingsNames.set(propertyName, idName);
}
- changes.replaceNode(file, parent_28, ts.createIdentifier(idName));
+ changes.replaceNode(file, parent, ts.createIdentifier(idName));
}
else {
needDefaultImport = true;
@@ -98755,7 +100509,7 @@ var ts;
// If it was unused, ensure that we at least import *something*.
needDefaultImport = true;
}
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
}
// Identifiers helpers
function makeUniqueName(name, identifiers) {
@@ -98797,17 +100551,9 @@ var ts;
}
function makeSingleImport(localName, propertyName, moduleSpecifier) {
return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
}
- function makeImport(name, namedImports, moduleSpecifier) {
- return makeImportDeclaration(name, namedImports, moduleSpecifier);
- }
- function makeImportDeclaration(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
- }
- codefix.makeImportDeclaration = makeImportDeclaration;
function makeImportSpecifier(propertyName, name) {
return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
}
@@ -98968,7 +100714,7 @@ var ts;
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, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier;
+ 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)) };
}
@@ -99014,11 +100760,11 @@ var ts;
if (context.symbolToken && ts.isIdentifier(context.symbolToken)) {
for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) {
var declaration = existingImports_1[_i].declaration;
- var namespace = getNamespaceImportName(declaration);
- if (namespace) {
- var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace));
+ var namespace_2 = getNamespaceImportName(declaration);
+ if (namespace_2) {
+ var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2));
if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) {
- useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken));
+ useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken));
}
}
}
@@ -99085,12 +100831,6 @@ var ts;
return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile);
}
}
- function usesJsExtensionOnImports(sourceFile) {
- return ts.firstDefined(sourceFile.imports, function (_a) {
- var text = _a.text;
- return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined;
- }) || false;
- }
function createImportClauseOfKind(kind, symbolName) {
var id = ts.createIdentifier(symbolName);
switch (kind) {
@@ -99104,274 +100844,15 @@ var ts;
ts.Debug.assertNever(kind);
}
}
- function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) {
- var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
- var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
- var addJsExtension = usesJsExtensionOnImports(sourceFile);
+ function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) {
var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind;
- var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) {
- var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName);
- var global = tryGetModuleNameFromAmbientModule(moduleSymbol)
- || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension)
- || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory)
- || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName);
- if (global) {
- return [global];
- }
- var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension);
- if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
- return [relativePath];
- }
- var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
- if (!relativeToBaseUrl) {
- return [relativePath];
- }
- var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension);
- if (paths) {
- var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
- if (fromPaths) {
- return [fromPaths];
- }
- }
- if (preferences.importModuleSpecifierPreference === "non-relative") {
- return [importRelativeToBaseUrl];
- }
- if (preferences.importModuleSpecifierPreference !== undefined)
- ts.Debug.assertNever(preferences.importModuleSpecifierPreference);
- if (isPathRelativeToParent(relativeToBaseUrl)) {
- return [relativePath];
- }
- /*
- Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl.
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/a/b
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../../foo/bar
- getRelativePathNParents(relativePath) = 2
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 2 < 2 = false
- In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar".
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/foo/a
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../a
- getRelativePathNParents(relativePath) = 1
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 1 < 2 = true
- In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
- */
- var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName);
- var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
- return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
- });
+ var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences);
return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ 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; }));
}
- /**
- * Looks for a existing imports that use symlinks to this module.
- * Only if no symlink is available, the real path will be used.
- */
- function getAllModulePaths(program, _a) {
- var fileName = _a.fileName;
- var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) {
- return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
- return res && res.resolvedFileName === fileName ? res.originalPath : undefined;
- });
- });
- return symlinks.length === 0 ? [fileName] : symlinks;
- }
- function getRelativePathNParents(relativePath) {
- var count = 0;
- for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) {
- count++;
- }
- return count;
- }
- function tryGetModuleNameFromAmbientModule(moduleSymbol) {
- var decl = moduleSymbol.valueDeclaration;
- if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) {
- return decl.name.text;
- }
- }
- function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
- for (var key in paths) {
- for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
- var patternText_1 = _a[_i];
- var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
- var indexOfStar = pattern.indexOf("*");
- if (indexOfStar === 0 && pattern.length === 1) {
- continue;
- }
- else if (indexOfStar !== -1) {
- var prefix = pattern.substr(0, indexOfStar);
- var suffix = pattern.substr(indexOfStar + 1);
- if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
- ts.startsWith(relativeToBaseUrl, prefix) &&
- ts.endsWith(relativeToBaseUrl, suffix)) {
- var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
- return key.replace("*", matchedStar);
- }
- }
- else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
- return key;
- }
- }
- }
- }
- function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
- var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
- if (normalizedTargetPath === undefined) {
- return undefined;
- }
- var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
- var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath;
- return ts.removeFileExtension(relativePath);
- }
- function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
- var roots = ts.getEffectiveTypeRoots(options, host);
- return ts.firstDefined(roots, function (unNormalizedTypeRoot) {
- var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName);
- if (ts.startsWith(moduleFileName, typeRoot)) {
- // For a type definition, we can strip `/index` even with classic resolution.
- return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension);
- }
- });
- }
- function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) {
- if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
- // nothing to do here
- return undefined;
- }
- var parts = getNodeModulePathParts(moduleFileName);
- if (!parts) {
- return undefined;
- }
- // Simplify the full file path to something that can be resolved by Node.
- // If the module could be imported by a directory name, use that directory's name
- var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
- // Get a path that's relative to node_modules or the importing file's path
- moduleSpecifier = getNodeResolvablePath(moduleSpecifier);
- // If the module was found in @types, get the actual Node package name
- return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier);
- function getDirectoryOrExtensionlessFileName(path) {
- // If the file is the main module, it can be imported by the package name
- var packageRootPath = path.substring(0, parts.packageRootIndex);
- var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
- if (host.fileExists(packageJsonPath)) {
- var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
- if (packageJsonContent) {
- var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
- if (mainFileRelative) {
- var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
- if (mainExportFile === getCanonicalFileName(path)) {
- return packageRootPath;
- }
- }
- }
- }
- // We still have a file name - remove the extension
- var fullModulePathWithoutExtension = ts.removeFileExtension(path);
- // If the file is /index, it can be imported by its directory name
- if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") {
- return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
- }
- return fullModulePathWithoutExtension;
- }
- function getNodeResolvablePath(path) {
- var basePath = path.substring(0, parts.topLevelNodeModulesIndex);
- if (sourceDirectory.indexOf(basePath) === 0) {
- // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
- return path.substring(parts.topLevelPackageNameIndex + 1);
- }
- else {
- return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName);
- }
- }
- }
- function getNodeModulePathParts(fullPath) {
- // If fullPath can't be valid module file within node_modules, returns undefined.
- // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
- // Returns indices: ^ ^ ^ ^
- var topLevelNodeModulesIndex = 0;
- var topLevelPackageNameIndex = 0;
- var packageRootIndex = 0;
- var fileNameIndex = 0;
- var States;
- (function (States) {
- States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
- States[States["NodeModules"] = 1] = "NodeModules";
- States[States["Scope"] = 2] = "Scope";
- States[States["PackageContent"] = 3] = "PackageContent";
- })(States || (States = {}));
- var partStart = 0;
- var partEnd = 0;
- var state = 0 /* BeforeNodeModules */;
- while (partEnd >= 0) {
- partStart = partEnd;
- partEnd = fullPath.indexOf("/", partStart + 1);
- switch (state) {
- case 0 /* BeforeNodeModules */:
- if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
- topLevelNodeModulesIndex = partStart;
- topLevelPackageNameIndex = partEnd;
- state = 1 /* NodeModules */;
- }
- break;
- case 1 /* NodeModules */:
- case 2 /* Scope */:
- if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
- state = 2 /* Scope */;
- }
- else {
- packageRootIndex = partEnd;
- state = 3 /* PackageContent */;
- }
- break;
- case 3 /* PackageContent */:
- if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
- state = 1 /* NodeModules */;
- }
- else {
- state = 3 /* PackageContent */;
- }
- break;
- }
- }
- fileNameIndex = partStart;
- return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
- }
- function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
- return ts.firstDefined(rootDirs, function (rootDir) {
- var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
- return isPathRelativeToParent(relativePath) ? undefined : relativePath;
- });
- }
- function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) {
- var noExtension = ts.removeFileExtension(fileName);
- return addJsExtension
- ? noExtension + ".js"
- : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs
- ? ts.removeSuffix(noExtension, "/index")
- : noExtension;
- }
- function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
- var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
- }
- function isPathRelativeToParent(path) {
- return ts.startsWith(path, "..");
- }
function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) {
var fromExistingImport = ts.firstDefined(existingImports, function (_a) {
var declaration = _a.declaration, importKind = _a.importKind;
@@ -99390,7 +100871,7 @@ var ts;
var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier);
var newImportInfos = existingDeclaration
? [existingDeclaration]
- : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences);
+ : 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));
@@ -99469,10 +100950,10 @@ var ts;
}
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_29 = token.parent;
- var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent_29);
- if ((ts.isJsxOpeningLikeElement && parent_29.tagName === token) || parent_29.kind === 259 /* JsxOpeningFragment */) {
- umdSymbol = checker.resolveName(checker.getJsxNamespace(parent_29), isNodeOpeningLikeElement ? parent_29.tagName : parent_29, 67216319 /* Value */, /*excludeGlobals*/ false);
+ var parent = token.parent;
+ var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent);
+ if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 259 /* JsxOpeningFragment */) {
+ umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false);
}
}
if (ts.isUMDExportSymbol(umdSymbol)) {
@@ -99686,9 +101167,9 @@ var ts;
}
else {
var meaning = ts.getMeaningFromLocation(node);
- var name_73 = ts.getTextOfNode(node);
- ts.Debug.assert(name_73 !== undefined, "name should be defined");
- suggestion = checker.getSuggestionForNonexistentSymbol(node, name_73, convertSemanticMeaningToSymbolFlags(meaning));
+ var name = ts.getTextOfNode(node);
+ ts.Debug.assert(name !== undefined, "name should be defined");
+ suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
}
return suggestion === undefined ? undefined : { node: node, suggestion: suggestion };
}
@@ -99848,7 +101329,24 @@ var ts;
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName,
/*questionToken*/ undefined, typeNode,
/*initializer*/ undefined);
- changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
+ if (lastProp) {
+ changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property);
+ }
+ else {
+ changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ }
+ }
+ // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
+ function getNodeToInsertPropertyAfter(cls) {
+ var res;
+ for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ if (!ts.isPropertyDeclaration(member))
+ break;
+ res = member;
+ }
+ return res;
}
function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) {
// Index signatures cannot have the static modifier.
@@ -100160,6 +101658,7 @@ var ts;
ts.Diagnostics._0_is_declared_but_never_used.code,
ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
+ ts.Diagnostics.All_destructured_elements_are_unused.code,
];
codefix.registerCodeFix({
errorCodes: errorCodes,
@@ -100170,9 +101669,13 @@ var ts;
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(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, context.span.start, /*deleted*/ undefined); });
+ if (delDestructure.length) {
+ return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, 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); });
+ var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); });
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));
}
@@ -100183,36 +101686,69 @@ var ts;
return result;
},
fixIds: [fixIdPrefix, fixIdDelete],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- var sourceFile = context.sourceFile;
- var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file);
- switch (context.fixId) {
- case fixIdPrefix:
- if (ts.isIdentifier(token) && canPrefix(token)) {
- tryPrefixDeclaration(changes, diag.code, sourceFile, token);
- }
- break;
- case fixIdDelete:
- var importDecl = tryGetFullImport(diag.file, diag.start);
- if (importDecl) {
- changes.deleteNode(sourceFile, importDecl);
- }
- else {
- tryDeleteDeclaration(changes, sourceFile, token);
- }
- break;
- default:
- ts.Debug.fail(JSON.stringify(context.fixId));
- }
- }); },
+ 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 NodeSet();
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var sourceFile = context.sourceFile;
+ var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file);
+ 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(diag.file, diag.start);
+ if (importDecl) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) {
+ tryDeleteDeclaration(changes, sourceFile, token, deleted);
+ }
+ }
+ break;
+ default:
+ ts.Debug.fail(JSON.stringify(context.fixId));
+ }
+ });
+ },
});
// Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
function tryGetFullImport(sourceFile, pos) {
var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined;
}
+ function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) {
+ var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent))
+ return false;
+ var decl = startToken.parent.parent;
+ switch (decl.kind) {
+ case 231 /* VariableDeclaration */:
+ tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors);
+ break;
+ case 148 /* Parameter */:
+ if (deletedAncestors)
+ deletedAncestors.add(decl);
+ changes.deleteNodeInList(sourceFile, decl);
+ break;
+ case 181 /* BindingElement */:
+ if (deletedAncestors)
+ deletedAncestors.add(decl);
+ changes.deleteNode(sourceFile, decl);
+ break;
+ default:
+ return ts.Debug.assertNever(decl);
+ }
+ return true;
+ }
function getToken(sourceFile, pos) {
- var token = ts.findPrecedingToken(pos, sourceFile);
+ 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;
}
@@ -100237,38 +101773,45 @@ var ts;
}
return false;
}
- function tryDeleteDeclaration(changes, sourceFile, token) {
+ function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors) {
switch (token.kind) {
case 71 /* Identifier */:
- tryDeleteIdentifier(changes, sourceFile, token);
+ tryDeleteIdentifier(changes, sourceFile, token, deletedAncestors);
break;
case 151 /* PropertyDeclaration */:
case 245 /* NamespaceImport */:
+ if (deletedAncestors)
+ deletedAncestors.add(token.parent);
changes.deleteNode(sourceFile, token.parent);
break;
default:
- tryDeleteDefault(changes, sourceFile, token);
+ tryDeleteDefault(changes, sourceFile, token, deletedAncestors);
}
}
- function tryDeleteDefault(changes, sourceFile, token) {
+ function tryDeleteDefault(changes, sourceFile, token, deletedAncestors) {
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);
}
}
- function tryDeleteIdentifier(changes, sourceFile, identifier) {
+ function tryDeleteIdentifier(changes, sourceFile, identifier, deletedAncestors) {
var parent = identifier.parent;
switch (parent.kind) {
case 231 /* VariableDeclaration */:
- tryDeleteVariableDeclaration(changes, sourceFile, parent);
+ tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors);
break;
case 147 /* TypeParameter */:
- var typeParameters = parent.parent.typeParameters;
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent);
if (typeParameters.length === 1) {
- var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false);
- var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false);
+ 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);
@@ -100299,6 +101842,20 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
+ case 181 /* BindingElement */: {
+ var pattern = parent.parent;
+ switch (pattern.kind) {
+ case 180 /* ArrayBindingPattern */:
+ changes.deleteNode(sourceFile, parent); // Don't delete ','
+ break;
+ case 179 /* ObjectBindingPattern */:
+ changes.deleteNodeInList(sourceFile, parent);
+ break;
+ default:
+ return ts.Debug.assertNever(pattern);
+ }
+ break;
+ }
// handle case where 'import a = A;'
case 242 /* ImportEqualsDeclaration */:
var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */);
@@ -100337,7 +101894,7 @@ var ts;
tryDeleteNamedImportBinding(changes, sourceFile, parent);
break;
default:
- tryDeleteDefault(changes, sourceFile, identifier);
+ tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors);
break;
}
}
@@ -100360,15 +101917,19 @@ var ts;
}
}
// token.parent is a variableDeclaration
- function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) {
+ function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) {
switch (varDecl.parent.parent.kind) {
case 219 /* 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;
@@ -100377,6 +101938,8 @@ var ts;
var forOfStatement = varDecl.parent.parent;
ts.Debug.assert(forOfStatement.initializer.kind === 232 /* VariableDeclarationList */);
var forOfInitializer = forOfStatement.initializer;
+ if (deletedAncestors)
+ deletedAncestors.add(forOfInitializer.declarations[0]);
changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral());
break;
case 220 /* ForInStatement */:
@@ -100385,13 +101948,131 @@ var ts;
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);
}
}
}
+ var NodeSet = /** @class */ (function () {
+ function NodeSet() {
+ this.map = ts.createMap();
+ }
+ NodeSet.prototype.add = function (node) {
+ this.map.set(String(ts.getNodeId(node)), node);
+ };
+ NodeSet.prototype.some = function (pred) {
+ return ts.forEachEntry(this.map, pred) || false;
+ };
+ return NodeSet;
+ }());
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "fixUnreachableCode";
+ var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)];
+ },
+ fixIds: [fixId],
+ 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 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 216 /* IfStatement */:
+ if (container.elseStatement) {
+ if (ts.isBlock(statement.parent)) {
+ changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements));
+ }
+ else {
+ changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray));
+ }
+ break;
+ }
+ // falls through
+ case 218 /* WhileStatement */:
+ case 219 /* ForStatement */:
+ changes.deleteNode(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);
+ }
+ }
+ }
+ function shouldRemove(s) {
+ // Don't remove statements that can validly be used before they appear.
+ return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) &&
+ // `var x;` may declare a variable used above
+ !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
+ }
+ function isPurelyTypeDeclaration(s) {
+ switch (s.kind) {
+ case 235 /* InterfaceDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ return true;
+ case 238 /* ModuleDeclaration */:
+ return ts.getModuleInstanceState(s) !== 1 /* Instantiated */;
+ case 237 /* EnumDeclaration */:
+ return ts.hasModifier(s, 2048 /* Const */);
+ }
+ }
+ function sliceAfter(arr, value) {
+ var index = arr.indexOf(value);
+ ts.Debug.assert(index !== -1);
+ return arr.slice(index);
+ }
+ // Calls 'cb' with the start and end of each range where 'pred' is true.
+ function split(arr, pred, cb) {
+ ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); });
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "fixUnusedLabel";
+ var errorCodes = [ts.Diagnostics.Unused_label.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
+ },
+ fixIds: [fixId],
+ 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 labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
+ var pos = token.getStart(sourceFile);
+ var statementPos = labeledStatement.statement.getStart(sourceFile);
+ // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
+ var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
+ : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
+ changes.deleteRange(sourceFile, { pos: pos, end: end });
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -100413,7 +102094,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 === 278 /* JSDocNullableType */) {
+ if (typeNode.kind === 280 /* 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, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -100433,7 +102114,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -100811,16 +102492,16 @@ var ts;
}
var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
var declaration;
- var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); });
+ 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)];
},
fixIds: [fixId],
getAllCodeActions: function (context) {
var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
- var seenFunctions = ts.createMap();
+ 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, seenFunctions);
+ doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen);
});
},
});
@@ -100834,7 +102515,7 @@ var ts;
return ts.Diagnostics.Infer_type_of_0_from_usage;
}
}
- function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) {
+ function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) {
if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) {
return undefined;
}
@@ -100843,17 +102524,18 @@ var ts;
// Variable and Property declarations
case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code:
case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
- if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
+ if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken);
return parent;
}
return undefined;
case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
var symbol = program.getTypeChecker().getSymbolAtLocation(token);
- if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) {
+ if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken);
return symbol.valueDeclaration;
}
+ return undefined;
}
}
var containingFunction = ts.getContainingFunction(token);
@@ -100869,7 +102551,7 @@ var ts;
}
// falls through
case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
- if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) {
+ if (markSeen(containingFunction)) {
var param = ts.cast(parent, ts.isParameter);
annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken);
return param;
@@ -101061,6 +102743,16 @@ var ts;
case 185 /* ElementAccessExpression */:
inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext);
break;
+ case 231 /* 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.
+ addCandidateType(usageContext, checker.getTypeAtLocation(initializer));
+ }
+ break;
+ }
+ }
+ // falls through
default:
return inferTypeFromContextualType(node, checker, usageContext);
}
@@ -101232,7 +102924,7 @@ var ts;
return checker.getStringType();
}
else if (usageContext.candidateTypes) {
- return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */));
+ return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker);
@@ -101349,7 +103041,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -101506,6 +103198,290 @@ var ts;
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
+// Used by importFixes to synthesize import module specifiers.
+/* @internal */
+var ts;
+(function (ts) {
+ var moduleSpecifiers;
+ (function (moduleSpecifiers) {
+ // For each symlink/original for a module, returns a list of ways to import that file.
+ function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) {
+ var compilerOptions = program.getCompilerOptions();
+ var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
+ var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
+ var addJsExtension = usesJsExtensionOnImports(importingSourceFile);
+ var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
+ var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName);
+ return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) {
+ var global = tryGetModuleNameFromAmbientModule(moduleSymbol)
+ || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension)
+ || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory)
+ || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName);
+ if (global) {
+ return [global];
+ }
+ var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension);
+ if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
+ return [relativePath];
+ }
+ var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
+ if (!relativeToBaseUrl) {
+ return [relativePath];
+ }
+ var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension);
+ if (paths) {
+ var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
+ if (fromPaths) {
+ return [fromPaths];
+ }
+ }
+ if (preferences.importModuleSpecifierPreference === "non-relative") {
+ return [importRelativeToBaseUrl];
+ }
+ if (preferences.importModuleSpecifierPreference !== undefined)
+ ts.Debug.assertNever(preferences.importModuleSpecifierPreference);
+ if (isPathRelativeToParent(relativeToBaseUrl)) {
+ return [relativePath];
+ }
+ /*
+ Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl.
+
+ Suppose we have:
+ baseUrl = /base
+ sourceDirectory = /base/a/b
+ moduleFileName = /base/foo/bar
+ Then:
+ relativePath = ../../foo/bar
+ getRelativePathNParents(relativePath) = 2
+ pathFromSourceToBaseUrl = ../../
+ getRelativePathNParents(pathFromSourceToBaseUrl) = 2
+ 2 < 2 = false
+ In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar".
+
+ Suppose we have:
+ baseUrl = /base
+ sourceDirectory = /base/foo/a
+ moduleFileName = /base/foo/bar
+ Then:
+ relativePath = ../a
+ getRelativePathNParents(relativePath) = 1
+ pathFromSourceToBaseUrl = ../../
+ getRelativePathNParents(pathFromSourceToBaseUrl) = 2
+ 1 < 2 = true
+ In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
+ */
+ var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName));
+ var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
+ return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
+ });
+ }
+ moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
+ function usesJsExtensionOnImports(_a) {
+ var imports = _a.imports;
+ return ts.firstDefined(imports, function (_a) {
+ var text = _a.text;
+ return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined;
+ }) || false;
+ }
+ /**
+ * Looks for a existing imports that use symlinks to this module.
+ * Only if no symlink is available, the real path will be used.
+ */
+ function getAllModulePaths(program, _a) {
+ var fileName = _a.fileName;
+ var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) {
+ return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
+ return res && res.resolvedFileName === fileName ? res.originalPath : undefined;
+ });
+ });
+ return symlinks.length === 0 ? [fileName] : symlinks;
+ }
+ function getRelativePathNParents(relativePath) {
+ var components = ts.getPathComponents(relativePath);
+ if (components[0] || components.length === 1)
+ return 0;
+ for (var i = 1; i < components.length; i++) {
+ if (components[i] !== "..")
+ return i - 1;
+ }
+ return components.length - 1;
+ }
+ function tryGetModuleNameFromAmbientModule(moduleSymbol) {
+ var decl = moduleSymbol.valueDeclaration;
+ if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) {
+ return decl.name.text;
+ }
+ }
+ function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
+ for (var key in paths) {
+ for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
+ var patternText_1 = _a[_i];
+ var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
+ var indexOfStar = pattern.indexOf("*");
+ if (indexOfStar === 0 && pattern.length === 1) {
+ continue;
+ }
+ else if (indexOfStar !== -1) {
+ var prefix = pattern.substr(0, indexOfStar);
+ var suffix = pattern.substr(indexOfStar + 1);
+ if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
+ ts.startsWith(relativeToBaseUrl, prefix) &&
+ ts.endsWith(relativeToBaseUrl, suffix)) {
+ var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
+ return key.replace("*", matchedStar);
+ }
+ }
+ else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
+ return key;
+ }
+ }
+ }
+ }
+ function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
+ var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
+ if (normalizedTargetPath === undefined) {
+ return undefined;
+ }
+ var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
+ var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
+ return ts.removeFileExtension(relativePath);
+ }
+ function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
+ var roots = ts.getEffectiveTypeRoots(options, host);
+ return ts.firstDefined(roots, function (unNormalizedTypeRoot) {
+ var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName);
+ if (ts.startsWith(moduleFileName, typeRoot)) {
+ // For a type definition, we can strip `/index` even with classic resolution.
+ return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension);
+ }
+ });
+ }
+ function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) {
+ if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
+ // nothing to do here
+ return undefined;
+ }
+ var parts = getNodeModulePathParts(moduleFileName);
+ if (!parts) {
+ return undefined;
+ }
+ // Simplify the full file path to something that can be resolved by Node.
+ // If the module could be imported by a directory name, use that directory's name
+ var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
+ // Get a path that's relative to node_modules or the importing file's path
+ moduleSpecifier = getNodeResolvablePath(moduleSpecifier);
+ // If the module was found in @types, get the actual Node package name
+ return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier);
+ function getDirectoryOrExtensionlessFileName(path) {
+ // If the file is the main module, it can be imported by the package name
+ var packageRootPath = path.substring(0, parts.packageRootIndex);
+ var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
+ if (host.fileExists(packageJsonPath)) {
+ var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
+ if (packageJsonContent) {
+ var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
+ if (mainFileRelative) {
+ var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
+ if (mainExportFile === getCanonicalFileName(path)) {
+ return packageRootPath;
+ }
+ }
+ }
+ }
+ // We still have a file name - remove the extension
+ var fullModulePathWithoutExtension = ts.removeFileExtension(path);
+ // If the file is /index, it can be imported by its directory name
+ if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") {
+ return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
+ }
+ return fullModulePathWithoutExtension;
+ }
+ function getNodeResolvablePath(path) {
+ var basePath = path.substring(0, parts.topLevelNodeModulesIndex);
+ if (sourceDirectory.indexOf(basePath) === 0) {
+ // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
+ return path.substring(parts.topLevelPackageNameIndex + 1);
+ }
+ else {
+ return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName));
+ }
+ }
+ }
+ function getNodeModulePathParts(fullPath) {
+ // If fullPath can't be valid module file within node_modules, returns undefined.
+ // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
+ // Returns indices: ^ ^ ^ ^
+ var topLevelNodeModulesIndex = 0;
+ var topLevelPackageNameIndex = 0;
+ var packageRootIndex = 0;
+ var fileNameIndex = 0;
+ var States;
+ (function (States) {
+ States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
+ States[States["NodeModules"] = 1] = "NodeModules";
+ States[States["Scope"] = 2] = "Scope";
+ States[States["PackageContent"] = 3] = "PackageContent";
+ })(States || (States = {}));
+ var partStart = 0;
+ var partEnd = 0;
+ var state = 0 /* BeforeNodeModules */;
+ while (partEnd >= 0) {
+ partStart = partEnd;
+ partEnd = fullPath.indexOf("/", partStart + 1);
+ switch (state) {
+ case 0 /* BeforeNodeModules */:
+ if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
+ topLevelNodeModulesIndex = partStart;
+ topLevelPackageNameIndex = partEnd;
+ state = 1 /* NodeModules */;
+ }
+ break;
+ case 1 /* NodeModules */:
+ case 2 /* Scope */:
+ if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
+ state = 2 /* Scope */;
+ }
+ else {
+ packageRootIndex = partEnd;
+ state = 3 /* PackageContent */;
+ }
+ break;
+ case 3 /* PackageContent */:
+ if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
+ state = 1 /* NodeModules */;
+ }
+ else {
+ state = 3 /* PackageContent */;
+ }
+ break;
+ }
+ }
+ fileNameIndex = partStart;
+ return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
+ }
+ function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
+ return ts.firstDefined(rootDirs, function (rootDir) {
+ var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
+ return isPathRelativeToParent(relativePath) ? undefined : relativePath;
+ });
+ }
+ function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) {
+ var noExtension = ts.removeFileExtension(fileName);
+ return addJsExtension
+ ? noExtension + ".js"
+ : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs
+ ? ts.removeSuffix(noExtension, "/index")
+ : noExtension;
+ }
+ function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
+ return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
+ }
+ function isPathRelativeToParent(path) {
+ return ts.startsWith(path, "..");
+ }
+ })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
+})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
@@ -101575,7 +103551,40 @@ var ts;
}
}
function doChange(changes, sourceFile, info) {
- changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (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];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span;
+ var importType = getImportTypeNode(sourceFile, span.start);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start));
+ }); },
+ });
+ function getImportTypeNode(sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ ts.Debug.assert(token.kind === 91 /* ImportKeyword */);
+ ts.Debug.assert(token.parent.kind === 178 /* ImportType */);
+ return token.parent;
+ }
+ function doChange(changes, sourceFile, importType) {
+ var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true);
+ changes.replaceNode(sourceFile, importType, newTypeNode);
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
@@ -101593,7 +103602,7 @@ var ts;
* Exported for tests.
*/
function getAvailableActions(context) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
return undefined;
@@ -101662,7 +103671,7 @@ var ts;
extractSymbol.getAvailableActions = getAvailableActions;
/* Exported for tests */
function getEditsForAction(context, actionName) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
if (parsedFunctionIndexMatch) {
@@ -102774,8 +104783,8 @@ var ts;
i_1++;
}
// Note that we add the current node's type parameters *after* updating the corresponding scope.
- if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) {
- for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) {
+ if (ts.isDeclarationWithTypeParameters(curr)) {
+ for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) {
var typeParameterDecl = _b[_a];
var typeParameter = checker.getTypeAtLocation(typeParameterDecl);
if (allTypeParameterUsages.has(typeParameter.id.toString())) {
@@ -102797,7 +104806,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_17 = function (i) {
+ var _loop_19 = 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
@@ -102837,21 +104846,11 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_17(i);
+ _loop_19(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
- function hasTypeParameters(node) {
- return ts.isDeclarationWithTypeParameters(node) &&
- node.typeParameters !== undefined &&
- node.typeParameters.length > 0;
- }
function isInGenericContext(node) {
- for (; node; node = node.parent) {
- if (hasTypeParameters(node)) {
- return true;
- }
- }
- return false;
+ return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; });
}
function recordTypeParameterUsages(type) {
// PERF: This is potentially very expensive. `type` could be a library type with
@@ -103116,8 +105115,8 @@ 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, startPosition = context.startPosition;
- if (!getConvertibleFieldAtPosition(file, startPosition))
+ var file = context.file;
+ if (!getConvertibleFieldAtPosition(context, file))
return undefined;
return [{
name: actionName,
@@ -103131,27 +105130,46 @@ var ts;
}];
}
function getEditsForAction(context, _actionName) {
- var file = context.file, startPosition = context.startPosition;
- var fieldInfo = getConvertibleFieldAtPosition(file, startPosition);
+ var file = context.file;
+ var fieldInfo = getConvertibleFieldAtPosition(context, file);
if (!fieldInfo)
return undefined;
var isJS = ts.isSourceFileJavaScript(file);
var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor;
+ ts.suppressLeadingAndTrailingTrivia(fieldName);
+ ts.suppressLeadingAndTrailingTrivia(declaration);
+ ts.suppressLeadingAndTrailingTrivia(container);
var isInClassLike = ts.isClassLike(container);
+ // avoid Readonly modifier because it will convert to get accessor
+ var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
var accessorModifiers = isInClassLike
- ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers
+ ? !modifierFlags || modifierFlags & 8 /* Private */
+ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */)
+ : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
: undefined;
var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined;
- updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container);
+ updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
- var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(getAccessor);
insertAccessor(changeTracker, file, getAccessor, declaration, container);
- insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ if (isReadonly) {
+ // readonly modifier only existed in classLikeDeclaration
+ var constructor = ts.getFirstConstructorWithBody(container);
+ if (constructor) {
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ }
+ }
+ else {
+ var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(setAccessor);
+ insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ }
var edits = changeTracker.getChanges();
var renameFilename = file.fileName;
- var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1;
- var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false);
+ var nameNeedRename = renameAccessor ? accessorName : fieldName;
+ var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
+ var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration));
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function isConvertableName(name) {
@@ -103171,24 +105189,32 @@ var ts;
var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined);
return modifiers && ts.createNodeArray(modifiers);
}
- function getConvertibleFieldAtPosition(file, startPosition) {
+ 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);
var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
- // make sure propertyDeclaration have AccessibilityModifier or Static Modifier
- var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */;
- if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
+ // 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)
+ || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
return undefined;
- var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name);
- var accessorName = createPropertyName(declaration.name.text, declaration.name);
- ts.suppressLeadingAndTrailingTrivia(fieldName);
- ts.suppressLeadingAndTrailingTrivia(declaration);
+ var name = declaration.name.text;
+ var startWithUnderscore = startsWithUnderscore(name);
+ var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file.text), declaration.name);
+ var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file.text) : name, declaration.name);
return {
isStatic: ts.hasStaticModifier(declaration),
+ isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent,
+ originalName: declaration.name,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
+ renameAccessor: startWithUnderscore
};
}
function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
@@ -103212,16 +105238,11 @@ var ts;
var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
changeTracker.replaceNode(file, declaration, property);
}
- function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) {
- var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer);
- changeTracker.insertNodeAtClassStart(file, classLikeContainer, property);
- changeTracker.deleteNodeInList(file, declaration);
- }
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
- function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) {
+ function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
if (ts.isPropertyDeclaration(declaration)) {
updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
}
@@ -103229,19 +105250,636 @@ var ts;
updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
}
else {
- updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container);
+ changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
}
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
ts.isParameterPropertyDeclaration(declaration)
? changeTracker.insertNodeAtClassStart(file, container, accessor)
- : changeTracker.insertNodeAfter(file, declaration, accessor);
+ : ts.isPropertyAssignment(declaration)
+ ? changeTracker.insertNodeAfterComma(file, declaration, accessor)
+ : changeTracker.insertNodeAfter(file, declaration, accessor);
+ }
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ if (!constructor.body)
+ return;
+ var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
+ var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); });
+ ts.forEach(referenceEntries, function (entry) {
+ var parent = entry.parent;
+ var accessorName = ts.createIdentifier(fieldName.text);
+ var node = ts.isBinaryExpression(parent)
+ ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
+ : ts.isPropertyAccessExpression(parent)
+ ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
+ : ts.Debug.fail("Unexpected write access token");
+ changeTracker.replaceNode(file, parent, node);
+ });
}
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var refactorName = "Move to a new file";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
+ return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var statements = ts.Debug.assertDefined(getStatementsToMove(context));
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ });
+ function getFirstAndLastStatementToMove(context) {
+ var file = context.file;
+ var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
+ var statements = file.statements;
+ var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
+ if (startNodeIndex === -1)
+ return undefined;
+ // Can't only partially include the start node or be partially into the next node
+ if (range.pos > statements[startNodeIndex].getStart(file))
+ return undefined;
+ var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
+ // Can't be partially into the next node
+ if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
+ return undefined;
+ return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex };
+ }
+ function doChange(oldFile, program, toMove, changes, host) {
+ var checker = program.getTypeChecker();
+ var usage = getUsageInfo(oldFile, toMove.all, checker);
+ var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
+ var extension = ts.extensionFromPath(oldFile.fileName);
+ var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
+ var newFileNameWithExtension = newModuleName + extension;
+ // If previous file was global, this is easy.
+ changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName));
+ addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
+ }
+ // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file.
+ function getStatementsToMove(context) {
+ var statements = context.file.statements;
+ var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast;
+ var all = [];
+ var ranges = [];
+ var rangeToMove = statements.slice(first, afterLast);
+ ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) {
+ for (var i = start; i < afterEnd; i++)
+ all.push(rangeToMove[i]);
+ ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] });
+ });
+ return { all: all, ranges: ranges };
+ }
+ function isPureImport(node) {
+ switch (node.kind) {
+ case 243 /* ImportDeclaration */:
+ return true;
+ case 242 /* ImportEqualsDeclaration */:
+ return !ts.hasModifier(node, 1 /* Export */);
+ case 213 /* VariableStatement */:
+ return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
+ default:
+ return false;
+ }
+ }
+ function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
+ var cfg = program.getCompilerOptions().configFile;
+ if (!cfg)
+ return;
+ var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
+ var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
+ var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
+ var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
+ return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
+ });
+ if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
+ changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
+ }
+ }
+ function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) {
+ var checker = program.getTypeChecker();
+ if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
+ deleteMovedStatements(oldFile, toMove.ranges, changes);
+ return toMove.all;
+ }
+ var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
+ var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax);
+ if (importsFromNewFile) {
+ changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true);
+ }
+ deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
+ deleteMovedStatements(oldFile, toMove.ranges, changes);
+ updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
+ return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
+ }
+ function deleteMovedStatements(sourceFile, moved, changes) {
+ for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
+ var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last;
+ changes.deleteNodeRange(sourceFile, first_1, last_3);
+ }
+ }
+ function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
+ }
+ }
+ function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
+ var checker = program.getTypeChecker();
+ var _loop_20 = function (sourceFile) {
+ if (sourceFile === oldFile)
+ return "continue";
+ var _loop_21 = function (statement) {
+ forEachImportInStatement(statement, function (importNode) {
+ var shouldMove = function (name) {
+ var symbol = ts.isBindingElement(name.parent)
+ ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
+ : ts.skipAlias(checker.getSymbolAtLocation(name), checker);
+ return !!symbol && movedSymbols.has(symbol);
+ };
+ deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
+ var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
+ var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
+ if (newImportDeclaration)
+ changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
+ });
+ };
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ _loop_21(statement);
+ }
+ };
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ _loop_20(sourceFile);
+ }
+ }
+ function moduleSpecifierFromImport(i) {
+ return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier
+ : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
+ : i.initializer.arguments[0]);
+ }
+ function forEachImportInStatement(statement, cb) {
+ if (ts.isImportDeclaration(statement)) {
+ if (ts.isStringLiteral(statement.moduleSpecifier))
+ cb(statement);
+ }
+ else if (ts.isImportEqualsDeclaration(statement)) {
+ if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
+ cb(statement);
+ }
+ }
+ else if (ts.isVariableStatement(statement)) {
+ for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
+ cb(decl);
+ }
+ }
+ }
+ }
+ function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) {
+ var defaultImport;
+ var imports = [];
+ newFileNeedExport.forEach(function (symbol) {
+ if (symbol.escapedName === "default" /* Default */) {
+ defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol));
+ }
+ else {
+ imports.push(symbol.name);
+ }
+ });
+ return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports);
+ }
+ function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) {
+ path = ts.ensurePathIsNonModuleName(path);
+ if (useEs6Imports) {
+ var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
+ return ts.makeImportIfNecessary(defaultImport, specifiers, path);
+ }
+ else {
+ ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module.
+ var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
+ return bindingElements.length
+ ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
+ : undefined;
+ }
+ }
+ function makeVariableStatement(name, type, initializer, flags) {
+ if (flags === void 0) { flags = 2 /* Const */; }
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
+ }
+ function createRequireCall(moduleSpecifier) {
+ return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
+ }
+ function addExports(sourceFile, toMove, needExport, useEs6Exports) {
+ return ts.flatMap(toMove, function (statement) {
+ if (isTopLevelDeclarationStatement(statement) &&
+ !isExported(sourceFile, statement, useEs6Exports) &&
+ forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
+ var exports_2 = addExport(statement, useEs6Exports);
+ if (exports_2)
+ return exports_2;
+ }
+ return statement;
+ });
+ }
+ function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
+ switch (importDecl.kind) {
+ case 243 /* ImportDeclaration */:
+ deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ case 242 /* ImportEqualsDeclaration */:
+ if (isUnused(importDecl.name)) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ break;
+ case 231 /* VariableDeclaration */:
+ deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ default:
+ ts.Debug.assertNever(importDecl);
+ }
+ }
+ function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
+ if (!importDecl.importClause)
+ return;
+ var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ var defaultUnused = !name || isUnused(name);
+ var namedBindingsUnused = !namedBindings ||
+ (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
+ if (defaultUnused && namedBindingsUnused) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (name && defaultUnused) {
+ changes.deleteNode(sourceFile, name);
+ }
+ if (namedBindings) {
+ if (namedBindingsUnused) {
+ changes.deleteNode(sourceFile, namedBindings);
+ }
+ else if (namedBindings.kind === 246 /* NamedImports */) {
+ for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
+ var element = _b[_i];
+ if (isUnused(element.name))
+ changes.deleteNodeInList(sourceFile, element);
+ }
+ }
+ }
+ }
+ }
+ function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
+ var name = varDecl.name;
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ if (isUnused(name)) {
+ changes.deleteNode(sourceFile, name);
+ }
+ break;
+ case 180 /* ArrayBindingPattern */:
+ break;
+ case 179 /* 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);
+ }
+ 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);
+ }
+ }
+ }
+ break;
+ }
+ }
+ function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) {
+ var copiedOldImports = [];
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var oldStatement = _a[_i];
+ forEachImportInStatement(oldStatement, function (i) {
+ ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
+ });
+ }
+ // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
+ var oldFileDefault;
+ var oldFileNamedImports = [];
+ var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
+ newFileImportsFromOldFile.forEach(function (symbol) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (!isTopLevelDeclaration(decl))
+ continue;
+ var name = nameOfTopLevelDeclaration(decl);
+ if (!name)
+ continue;
+ var top = getTopLevelDeclarationStatement(decl);
+ if (markSeenTop(top)) {
+ addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
+ }
+ if (ts.hasModifier(decl, 512 /* Default */)) {
+ oldFileDefault = name;
+ }
+ else {
+ oldFileNamedImports.push(name.text);
+ }
+ }
+ });
+ ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax));
+ return copiedOldImports;
+ }
+ function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
+ var newModuleName = moduleName;
+ for (var i = 1;; i++) {
+ var name = ts.combinePaths(inDirectory, newModuleName + extension);
+ if (!host.fileExists(name))
+ return newModuleName;
+ newModuleName = moduleName + "." + i;
+ }
+ }
+ function getNewModuleName(movedSymbols) {
+ return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
+ }
+ function getUsageInfo(oldFile, toMove, checker) {
+ var movedSymbols = new SymbolSet();
+ var oldImportsNeededByNewFile = new SymbolSet();
+ var newFileImportsFromOldFile = new SymbolSet();
+ for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
+ var statement = toMove_1[_i];
+ forEachTopLevelDeclaration(statement, function (decl) {
+ movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
+ });
+ }
+ for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
+ var statement = toMove_2[_a];
+ forEachReference(statement, checker, function (symbol) {
+ if (!symbol.declarations)
+ return;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (isInImport(decl)) {
+ oldImportsNeededByNewFile.add(symbol);
+ }
+ else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) {
+ newFileImportsFromOldFile.add(symbol);
+ }
+ }
+ });
+ }
+ var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
+ var oldFileImportsFromNewFile = new SymbolSet();
+ for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
+ var statement = _c[_b];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachReference(statement, checker, function (symbol) {
+ if (movedSymbols.has(symbol))
+ oldFileImportsFromNewFile.add(symbol);
+ unusedImportsFromOldFile.delete(symbol);
+ });
+ }
+ return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
+ }
+ // Below should all be utilities
+ function isInImport(decl) {
+ switch (decl.kind) {
+ case 242 /* ImportEqualsDeclaration */:
+ case 247 /* ImportSpecifier */:
+ case 244 /* ImportClause */:
+ return true;
+ case 231 /* VariableDeclaration */:
+ return isVariableDeclarationInImport(decl);
+ case 181 /* BindingElement */:
+ return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
+ default:
+ return false;
+ }
+ }
+ function isVariableDeclarationInImport(decl) {
+ return ts.isSourceFile(decl.parent.parent.parent) &&
+ decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
+ }
+ function filterImport(i, moduleSpecifier, keep) {
+ switch (i.kind) {
+ case 243 /* ImportDeclaration */: {
+ var clause = i.importClause;
+ if (!clause)
+ return undefined;
+ var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
+ var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
+ return defaultImport || namedBindings
+ ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
+ : undefined;
+ }
+ case 242 /* ImportEqualsDeclaration */:
+ return keep(i.name) ? i : undefined;
+ case 231 /* VariableDeclaration */: {
+ var name = filterBindingName(i.name, keep);
+ return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
+ }
+ default:
+ return ts.Debug.assertNever(i);
+ }
+ }
+ function filterNamedBindings(namedBindings, keep) {
+ if (namedBindings.kind === 245 /* NamespaceImport */) {
+ return keep(namedBindings.name) ? namedBindings : undefined;
+ }
+ else {
+ var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
+ return newElements.length ? ts.createNamedImports(newElements) : undefined;
+ }
+ }
+ function filterBindingName(name, keep) {
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ return keep(name) ? name : undefined;
+ case 180 /* ArrayBindingPattern */:
+ return name;
+ case 179 /* 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;
+ }
+ }
+ }
+ function forEachReference(node, checker, onReference) {
+ node.forEachChild(function cb(node) {
+ if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
+ var sym = checker.getSymbolAtLocation(node);
+ if (sym)
+ onReference(sym);
+ }
+ else {
+ node.forEachChild(cb);
+ }
+ });
+ }
+ var SymbolSet = /** @class */ (function () {
+ function SymbolSet() {
+ this.map = ts.createMap();
+ }
+ SymbolSet.prototype.add = function (symbol) {
+ this.map.set(String(ts.getSymbolId(symbol)), symbol);
+ };
+ SymbolSet.prototype.has = function (symbol) {
+ return this.map.has(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.delete = function (symbol) {
+ this.map.delete(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ SymbolSet.prototype.forEachEntry = function (cb) {
+ return ts.forEachEntry(this.map, cb);
+ };
+ SymbolSet.prototype.clone = function () {
+ var clone = new SymbolSet();
+ ts.copyEntries(this.map, clone.map);
+ return clone;
+ };
+ return SymbolSet;
+ }());
+ function isTopLevelDeclaration(node) {
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
+ }
+ function isTopLevelDeclarationStatement(node) {
+ ts.Debug.assert(ts.isSourceFile(node.parent));
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
+ }
+ function isNonVariableTopLevelDeclaration(node) {
+ switch (node.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function forEachTopLevelDeclaration(statement, cb) {
+ switch (statement.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return cb(statement);
+ case 213 /* VariableStatement */:
+ return ts.forEach(statement.declarationList.declarations, cb);
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */
+ ? cb(statement)
+ : undefined;
+ }
+ }
+ }
+ function nameOfTopLevelDeclaration(d) {
+ return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
+ }
+ function getTopLevelDeclarationStatement(d) {
+ return ts.isVariableDeclaration(d) ? d.parent.parent : d;
+ }
+ function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
+ if (isExported(sourceFile, decl, useEs6Exports))
+ return;
+ if (useEs6Exports) {
+ if (!ts.isExpressionStatement(decl))
+ changes.insertExportModifier(sourceFile, decl);
+ }
+ else {
+ var names = getNamesToExportInCommonJS(decl);
+ if (names.length !== 0)
+ changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
+ }
+ }
+ function isExported(sourceFile, decl, useEs6Exports) {
+ if (useEs6Exports) {
+ return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
+ }
+ else {
+ return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
+ }
+ }
+ function addExport(decl, useEs6Exports) {
+ return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
+ }
+ function addEs6Export(d) {
+ var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
+ switch (d.kind) {
+ case 233 /* FunctionDeclaration */:
+ return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
+ case 234 /* ClassDeclaration */:
+ return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 213 /* VariableStatement */:
+ return ts.updateVariableStatement(d, modifiers, d.declarationList);
+ case 238 /* ModuleDeclaration */:
+ return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
+ case 237 /* EnumDeclaration */:
+ return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
+ case 236 /* TypeAliasDeclaration */:
+ return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
+ case 235 /* InterfaceDeclaration */:
+ return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 242 /* ImportEqualsDeclaration */:
+ return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ return ts.Debug.assertNever(d);
+ }
+ }
+ function addCommonjsExport(decl) {
+ return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment));
+ }
+ function getNamesToExportInCommonJS(decl) {
+ switch (decl.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ return [decl.name.text];
+ case 213 /* VariableStatement */:
+ return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return undefined;
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ ts.Debug.assertNever(decl);
+ }
+ }
+ /** Creates `exports.x = x;` */
+ function createExportAssignment(name) {
+ return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name)));
+ }
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var sourcemaps;
(function (sourcemaps) {
@@ -103563,7 +106201,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 297 /* LastJSDocNode */; });
return child.kind < 145 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -103633,7 +106271,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(298 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
@@ -104156,6 +106794,9 @@ var ts;
HostCache.prototype.compilationSettings = function () {
return this._compilationSettings;
};
+ HostCache.prototype.getProjectReferences = function () {
+ return this.host.getProjectReferences && this.host.getProjectReferences();
+ };
HostCache.prototype.createEntry = function (fileName, path) {
var entry;
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
@@ -104185,9 +106826,18 @@ var ts;
return ts.isString(info) ? undefined : info;
};
HostCache.prototype.getRootFileNames = function () {
- return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) {
- return ts.isString(entry) ? entry : entry.hostFileName;
+ var names = [];
+ this.fileNameToEntry.forEach(function (entry) {
+ if (ts.isString(entry)) {
+ names.push(entry);
+ }
+ else {
+ if (entry.scriptKind !== 6 /* JSON */) {
+ names.push(entry.hostFileName);
+ }
+ }
});
+ return names;
};
HostCache.prototype.getVersion = function (path) {
var file = this.getHostFileInformation(path);
@@ -104363,6 +107013,7 @@ var ts;
}
ts.createSourceFileLikeCache = createSourceFileLikeCache;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
var syntaxTreeCache = new SyntaxTreeCache(host);
@@ -104466,7 +107117,14 @@ var ts;
};
}
var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
- program = ts.createProgram(rootFileNames, newSettings, compilerHost, program);
+ var options = {
+ rootNames: rootFileNames,
+ options: newSettings,
+ host: compilerHost,
+ oldProgram: program,
+ projectReferences: hostCache.getProjectReferences()
+ };
+ program = ts.createProgram(options);
// hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
// It needs to be cleared to allow all collected snapshots to be released
hostCache = undefined;
@@ -104670,6 +107328,11 @@ var ts;
}
return checker.getSymbolAtLocation(node);
}
+ function toLineColumnOffset(fileName, position) {
+ var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
+ var file = program.getSourceFile(path) || sourcemappedFileCache.get(path);
+ 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 base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
@@ -104731,8 +107394,8 @@ var ts;
}
possibleMapLocations.push(fileName + ".map");
for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) {
- var location_4 = possibleMapLocations_1[_i];
- var mapPath = ts.toPath(location_4, ts.getDirectoryPath(fileName), getCanonicalFileName);
+ var location = possibleMapLocations_1[_i];
+ var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName);
if (host.fileExists(mapPath)) {
return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath);
}
@@ -104741,27 +107404,28 @@ var ts;
}
function makeGetTargetOfMappedPosition(extract, create) {
return getTargetOfMappedPosition;
- function getTargetOfMappedPosition(input) {
+ function getTargetOfMappedPosition(input, original) {
+ if (original === void 0) { original = input; }
var info = extract(input);
if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) {
- var file = program.getSourceFile(info.fileName);
- if (!file) {
+ var file_18 = program.getSourceFile(info.fileName);
+ if (!file_18) {
var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName);
- file = sourcemappedFileCache.get(path);
+ file_18 = sourcemappedFileCache.get(path);
}
- if (!file) {
+ if (!file_18) {
return input;
}
- var mapper = getSourceMapper(info.fileName, file);
+ var mapper = getSourceMapper(info.fileName, file_18);
var newLoc = mapper.getOriginalPosition(info);
if (newLoc === info)
return input;
- return getTargetOfMappedPosition(create(newLoc, input));
+ return getTargetOfMappedPosition(create(newLoc, input, original), original);
}
return input;
}
}
- var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({
+ var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({
containerKind: info.containerKind,
containerName: info.containerName,
fileName: newLoc.fileName,
@@ -104770,10 +107434,12 @@ var ts;
textSpan: {
start: newLoc.position,
length: info.textSpan.length
- }
+ },
+ originalFileName: original.fileName,
+ originalTextSpan: original.textSpan
}); });
function getTargetOfMappedDeclarationFiles(infos) {
- return ts.map(infos, getTargetOfMappedDeclarationInfo);
+ return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); });
}
/// Goto definition
function getDefinitionAtPosition(fileName, position) {
@@ -104806,10 +107472,12 @@ var ts;
textSpan: {
start: newLoc.position,
length: info.textSpan.length
- }
+ },
+ originalFileName: info.fileName,
+ originalTextSpan: info.textSpan
}); });
function getTargetOfMappedImplementationLocations(infos) {
- return ts.map(infos, getTargetOfMappedImplementationLocation);
+ return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); });
}
function getImplementationAtPosition(fileName, position) {
synchronizeHostData();
@@ -105317,8 +107985,8 @@ var ts;
getProgram: getProgram,
getApplicableRefactors: getApplicableRefactors,
getEditsForRefactor: getEditsForRefactor,
+ toLineColumnOffset: toLineColumnOffset
};
- var _a;
}
ts.createLanguageService = createLanguageService;
/* @internal */
@@ -105389,20 +108057,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_6 = [];
+ var result_7 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_6.push(symbol);
+ result_7.push(symbol);
}
});
- return result_6;
+ return result_7;
}
if (symbol) {
- result_6.push(symbol);
- return result_6;
+ result_7.push(symbol);
+ return result_7;
}
}
return undefined;
@@ -105469,7 +108137,7 @@ var ts;
return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
- return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
+ return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
@@ -105484,7 +108152,7 @@ var ts;
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
- return spanInNode(ts.findNextToken(node, node.parent));
+ return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
}
function spanInNode(node) {
if (node) {
@@ -107042,8 +109710,8 @@ var ts;
var before = log && self.host.getMemoryUsage();
self.host.gc();
if (log) {
- var after = self.host.getMemoryUsage();
- self.logger.perftrc("GC::before " + before + ", after " + after);
+ var after_1 = self.host.getMemoryUsage();
+ self.logger.perftrc("GC::before " + before + ", after " + after_1);
}
};
return GcTimer;
@@ -107804,7 +110472,7 @@ var ts;
})(ProjectKind = server.ProjectKind || (server.ProjectKind = {}));
/* @internal */
function countEachFileTypes(infos) {
- var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 };
+ var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0, deferred: 0 };
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
switch (info.scriptKind) {
@@ -107822,6 +110490,9 @@ var ts;
case 4 /* TSX */:
result.tsx += 1;
break;
+ case 7 /* Deferred */:
+ result.deferred += 1;
+ break;
}
}
return result;
@@ -107905,7 +110576,7 @@ var ts;
this.compilerOptions.allowNonTsExtensions = true;
this.compilerOptions.allowJs = true;
}
- else if (hasExplicitListOfFiles || this.compilerOptions.allowJs) {
+ else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) {
// If files are listed explicitly or allowJs is specified, allow all extensions
this.compilerOptions.allowNonTsExtensions = true;
}
@@ -107976,6 +110647,9 @@ var ts;
Project.prototype.getProjectVersion = function () {
return this.projectStateVersion.toString();
};
+ Project.prototype.getProjectReferences = function () {
+ return undefined;
+ };
Project.prototype.getScriptFileNames = function () {
var _this = this;
if (!this.rootFiles) {
@@ -108045,6 +110719,9 @@ var ts;
Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) {
return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames);
};
+ Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) {
+ return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile);
+ };
Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile);
};
@@ -108426,15 +111103,16 @@ var ts;
* @returns: true if set of files in the project stays the same and false - otherwise.
*/
Project.prototype.updateGraph = function () {
+ var _a;
this.resolutionCache.startRecordingFilesWithChangedResolutions();
var hasNewProgram = this.updateGraphWorker();
var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles;
this.hasAddedorRemovedFiles = false;
var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray;
for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) {
- var file = changedFiles_1[_i];
+ var file_19 = changedFiles_1[_i];
// delete cached information for changed files
- this.cachedUnresolvedImportsPerFile.delete(file);
+ this.cachedUnresolvedImportsPerFile.delete(file_19);
}
// update builder only if language service is enabled
// otherwise tell it to drop its internal state
@@ -108448,11 +111126,11 @@ var ts;
if (hasNewProgram || changedFiles.length) {
var result = void 0;
var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); });
- for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _b = 0, _c = this.program.getSourceFiles(); _b < _c.length; _b++) {
+ var sourceFile = _c[_b];
var unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules);
if (unResolved !== server.emptyArray) {
- (_c = (result || (result = []))).push.apply(_c, unResolved);
+ (_a = (result || (result = []))).push.apply(_a, unResolved);
}
}
this.lastCachedUnresolvedImportsList = result ? server.toDeduplicatedSortedArray(result) : server.emptyArray;
@@ -108466,7 +111144,6 @@ var ts;
this.projectProgramVersion++;
}
return !hasNewProgram;
- var _c;
};
/*@internal*/
Project.prototype.updateTypingFiles = function (typingFiles) {
@@ -108578,9 +111255,9 @@ var ts;
var sourceFiles = this.program.getSourceFiles();
var strBuilder = "\tFiles (" + sourceFiles.length + ")\n";
if (writeProjectFileNames) {
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var file = sourceFiles_7[_i];
- strBuilder += "\t" + file.fileName + "\n";
+ for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
+ var file_20 = sourceFiles_8[_i];
+ strBuilder += "\t" + file_20.fileName + "\n";
}
}
return strBuilder;
@@ -108666,7 +111343,7 @@ var ts;
// ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.globalPlugins) {
- var _loop_18 = function (globalPluginName) {
+ var _loop_22 = function (globalPluginName) {
// Skip empty names from odd commandline parses
if (!globalPluginName)
return "continue";
@@ -108681,7 +111358,7 @@ var ts;
// Enable global plugins with synthetic configuration entries
for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
var globalPluginName = _a[_i];
- _loop_18(globalPluginName);
+ _loop_22(globalPluginName);
}
}
};
@@ -108691,15 +111368,19 @@ var ts;
var log = function (message) {
_this.projectService.logger.info(message);
};
- for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) {
- var searchPath = searchPaths_1[_i];
- var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log);
- if (resolvedModule) {
- this.enableProxy(resolvedModule, pluginConfigEntry);
- return;
- }
+ var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) {
+ return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log);
+ });
+ if (resolvedModule) {
+ this.enableProxy(resolvedModule, pluginConfigEntry);
}
- this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name);
+ else {
+ this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name);
+ }
+ };
+ /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
+ Project.prototype.refreshDiagnostics = function () {
+ this.projectService.sendProjectsUpdatedInBackgroundEvent();
};
Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) {
try {
@@ -108834,9 +111515,10 @@ var ts;
var ConfiguredProject = /** @class */ (function (_super) {
__extends(ConfiguredProject, _super);
/*@internal*/
- function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost) {
+ function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) {
var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
_this.compileOnSaveEnabled = compileOnSaveEnabled;
+ _this.projectReferences = projectReferences;
/** Ref count to the project when opened from external project */
_this.externalProjectRefCount = 0;
_this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName));
@@ -108867,6 +111549,12 @@ var ts;
ConfiguredProject.prototype.getConfigFilePath = function () {
return server.asNormalizedPath(this.getProjectName());
};
+ ConfiguredProject.prototype.getProjectReferences = function () {
+ return this.projectReferences;
+ };
+ ConfiguredProject.prototype.updateReferences = function (refs) {
+ this.projectReferences = refs;
+ };
ConfiguredProject.prototype.enablePlugins = function () {
var host = this.projectService.host;
var options = this.getCompilationSettings();
@@ -109025,6 +111713,7 @@ var ts;
server.ConfigFileDiagEvent = "configFileDiag";
server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
server.ProjectInfoTelemetryEvent = "projectInfo";
+ server.OpenFileInfoTelemetryEvent = "openFileInfo";
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) {
var map = ts.createMap();
for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) {
@@ -109197,6 +111886,8 @@ var ts;
* Container of all known scripts
*/
this.filenameToScriptInfo = ts.createMap();
+ // Set of all '.js' files ever opened.
+ this.allJsFilesForOpenFileTelemetry = ts.createMap();
/**
* maps external project file name to list of config files that were the part of this project
*/
@@ -109388,6 +112079,7 @@ var ts;
ProjectService.prototype.hasPendingProjectUpdate = function (project) {
return this.pendingProjectUpdates.has(project.getProjectName());
};
+ /* @internal */
ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () {
var _this = this;
if (!this.eventHandler) {
@@ -109407,11 +112099,13 @@ var ts;
this.delayEnsureProjectForOpenFiles();
};
ProjectService.prototype.delayUpdateProjectGraphs = function (projects) {
- for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) {
- var project = projects_2[_i];
- this.delayUpdateProjectGraph(project);
+ if (projects.length) {
+ for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) {
+ var project = projects_2[_i];
+ this.delayUpdateProjectGraph(project);
+ }
+ this.delayEnsureProjectForOpenFiles();
}
- this.delayEnsureProjectForOpenFiles();
};
ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) {
ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled");
@@ -109510,7 +112204,6 @@ var ts;
this.handleDeletedFile(info);
}
else if (!info.isScriptOpen()) {
- ts.Debug.assert(info.containingProjects.length !== 0);
// file has been changed which might affect the set of referenced files in projects that include
// this file and set of inferred projects
info.delayReloadNonMixedContentFile();
@@ -109632,7 +112325,7 @@ var ts;
}
project.updateGraph();
if (!this.useSingleInferredProject && !project.projectRootPath) {
- var _loop_19 = function (inferredProject) {
+ var _loop_23 = function (inferredProject) {
if (inferredProject === project || inferredProject.isOrphan()) {
return "continue";
}
@@ -109653,7 +112346,7 @@ var ts;
// Note that we need to create a copy of the array since the list of project can change
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var inferredProject = _a[_i];
- _loop_19(inferredProject);
+ _loop_23(inferredProject);
}
}
return project;
@@ -109927,13 +112620,17 @@ var ts;
* the newly opened file.
*/
ProjectService.prototype.forEachConfigFileLocation = function (info, action) {
+ var _this = this;
if (this.syntaxOnly) {
return undefined;
}
ts.Debug.assert(this.openFiles.has(info.path));
var projectRootPath = this.openFiles.get(info.path);
var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName));
- while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) {
+ var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); };
+ // If projectRootPath doesnt contain info.path, then do normal search for config file
+ var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot();
+ do {
var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json"));
var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json"));
@@ -109950,7 +112647,7 @@ var ts;
break;
}
searchPath = parentPath;
- }
+ } while (anySearchPathOk || isSearchPathInProjectRoot());
return undefined;
};
/**
@@ -110042,7 +112739,8 @@ var ts;
configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined,
wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories),
typeAcquisition: parsedCommandLine.typeAcquisition,
- compileOnSave: parsedCommandLine.compileOnSave
+ compileOnSave: parsedCommandLine.compileOnSave,
+ projectReferences: parsedCommandLine.projectReferences
};
return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs };
};
@@ -110098,11 +112796,11 @@ var ts;
return;
}
this.seenProjects.set(projectKey, true);
- if (!this.eventHandler) {
+ if (!this.eventHandler || !this.host.createSHA256Hash) {
return;
}
var data = {
- projectId: this.host.createHash(projectKey),
+ projectId: this.host.createSHA256Hash(projectKey),
fileStats: server.countEachFileTypes(project.getScriptInfos()),
compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
@@ -110145,7 +112843,7 @@ var ts;
var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs;
this.logger.info("Opened configuration file " + configFileName);
var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader);
- var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost);
+ var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences);
project.configFileSpecs = configFileSpecs;
// TODO: We probably should also watch the configFiles that are extended
project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project);
@@ -110252,6 +112950,7 @@ var ts;
// Update the project
project.configFileSpecs = configFileSpecs;
project.setProjectErrors(configFileErrors);
+ project.updateReferences(projectOptions.projectReferences);
var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader);
if (lastFileExceededProgramSize) {
project.disableLanguageService(lastFileExceededProgramSize);
@@ -110375,7 +113074,7 @@ var ts;
return projects;
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
- var _loop_20 = function (project) {
+ var _loop_24 = function (project) {
// Add the projects only if they can use symLink targets and not already in the list
if (project.languageServiceEnabled &&
!project.isOrphan() &&
@@ -110392,7 +113091,7 @@ var ts;
};
for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
- _loop_20(project);
+ _loop_24(project);
}
}
}
@@ -110709,8 +113408,16 @@ var ts;
}
});
this.printProjects();
+ this.telemetryOnOpenFile(info);
return { configFileName: configFileName, configFileErrors: configFileErrors };
};
+ ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) {
+ if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) {
+ return;
+ }
+ var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective };
+ this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } });
+ };
/**
* Close file whose contents is managed by the client
* @param filename is absolute pathname
@@ -110723,13 +113430,13 @@ var ts;
this.printProjects();
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_21 = function (proj) {
+ var _loop_25 = function (proj) {
var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; });
result.push(proj.getChangesSinceVersion(knownProject && knownProject.version));
};
for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) {
var proj = currentProjects_1[_i];
- _loop_21(proj);
+ _loop_25(proj);
}
};
/* @internal */
@@ -110744,25 +113451,25 @@ var ts;
ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
if (openFiles) {
for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
- var scriptInfo = this.getScriptInfo(file.fileName);
+ var file_21 = openFiles_1[_i];
+ var scriptInfo = this.getScriptInfo(file_21.fileName);
ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already");
- var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName);
- this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent);
+ var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file_21.fileName);
+ this.openClientFileWithNormalizedPath(normalizedPath, file_21.content, tryConvertScriptKindName(file_21.scriptKind), file_21.hasMixedContent);
}
}
if (changedFiles) {
for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) {
- var file = changedFiles_2[_a];
- var scriptInfo = this.getScriptInfo(file.fileName);
+ var file_22 = changedFiles_2[_a];
+ var scriptInfo = this.getScriptInfo(file_22.fileName);
ts.Debug.assert(!!scriptInfo);
- this.applyChangesToFile(scriptInfo, file.changes);
+ this.applyChangesToFile(scriptInfo, file_22.changes);
}
}
if (closedFiles) {
for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
+ var file_23 = closedFiles_1[_b];
+ this.closeClientFile(file_23);
}
}
};
@@ -110838,15 +113545,15 @@ var ts;
var excludeRules = [];
var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); });
var excludedFiles = [];
- var _loop_22 = function (name_74) {
- var rule = this_2.safelist[name_74];
+ var _loop_26 = function (name) {
+ var rule_2 = this_2.safelist[name];
for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) {
var root = normalizedNames_1[_i];
- if (rule.match.test(root)) {
- this_2.logger.info("Excluding files based on rule " + name_74 + " matching file '" + root + "'");
+ if (rule_2.match.test(root)) {
+ this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'");
// If the file matches, collect its types packages and exclude rules
- if (rule.types) {
- for (var _a = 0, _b = rule.types; _a < _b.length; _a++) {
+ if (rule_2.types) {
+ for (var _a = 0, _b = rule_2.types; _a < _b.length; _a++) {
var type = _b[_a];
// Best-effort de-duping here - doesn't need to be unduplicated but
// we don't want the list to become a 400-element array of just 'kendo'
@@ -110855,9 +113562,9 @@ var ts;
}
}
}
- if (rule.exclude) {
- var _loop_23 = function (exclude) {
- var processedRule = root.replace(rule.match, function () {
+ if (rule_2.exclude) {
+ var _loop_28 = function (exclude) {
+ var processedRule = root.replace(rule_2.match, function () {
var groups = [];
for (var _i = 0; _i < arguments.length; _i++) {
groups[_i] = arguments[_i];
@@ -110868,7 +113575,7 @@ var ts;
if (typeof groupNumberOrString === "number") {
if (!ts.isString(groups[groupNumberOrString])) {
// Specification was wrong - exclude nothing!
- _this.logger.info("Incorrect RegExp specification in safelist rule " + name_74 + " - not enough groups");
+ _this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups");
// * can't appear in a filename; escape it because it's feeding into a RegExp
return "\\*";
}
@@ -110881,9 +113588,9 @@ var ts;
excludeRules.push(processedRule);
}
};
- for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_2.exclude; _c < _d.length; _c++) {
var exclude = _d[_c];
- _loop_23(exclude);
+ _loop_28(exclude);
}
}
else {
@@ -110898,12 +113605,12 @@ var ts;
};
var this_2 = this;
for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) {
- var name_74 = _a[_i];
- _loop_22(name_74);
+ var name = _a[_i];
+ _loop_26(name);
}
var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); });
var filesToKeep = [];
- var _loop_24 = function (i) {
+ var _loop_27 = function (i) {
if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) {
excludedFiles.push(normalizedNames[i]);
}
@@ -110941,7 +113648,7 @@ var ts;
};
var this_3 = this;
for (var i = 0; i < proj.rootFiles.length; i++) {
- _loop_24(i);
+ _loop_27(i);
}
proj.rootFiles = filesToKeep;
return excludedFiles;
@@ -110963,15 +113670,15 @@ var ts;
var tsConfigFiles;
var rootFiles = [];
for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) {
- var file = _a[_i];
- var normalized = server.toNormalizedPath(file.fileName);
+ var file_24 = _a[_i];
+ var normalized = server.toNormalizedPath(file_24.fileName);
if (server.getBaseConfigFileName(normalized)) {
if (!this.syntaxOnly && this.host.fileExists(normalized)) {
(tsConfigFiles || (tsConfigFiles = [])).push(normalized);
}
}
else {
- rootFiles.push(file);
+ rootFiles.push(file_24);
}
}
// sort config files to simplify comparison later
@@ -111055,6 +113762,15 @@ var ts;
this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles);
}
};
+ ProjectService.prototype.hasDeferredExtension = function () {
+ for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) {
+ var extension = _a[_i];
+ if (extension.scriptKind === 7 /* Deferred */) {
+ return true;
+ }
+ }
+ return false;
+ };
/** Makes a filename safe to insert in a RegExp */
ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g;
return ProjectService;
@@ -111266,6 +113982,7 @@ var ts;
}
var Session = /** @class */ (function () {
function Session(opts) {
+ var _a;
var _this = this;
this.changeSeq = 0;
this.handlers = ts.createMapFromTemplate((_a = {},
@@ -111600,7 +114317,6 @@ var ts;
};
this.projectService = new server.ProjectService(settings);
this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger);
- var _a;
}
Session.prototype.sendRequestCompletedEvent = function (requestId) {
this.event({ request_seq: requestId }, "requestCompleted");
@@ -111862,9 +114578,7 @@ var ts;
if (simplifiedResult) {
return this.mapDefinitionInfo(definitions, project);
}
- else {
- return definitions;
- }
+ return definitions.map(Session.mapToOriginalLocation);
};
Session.prototype.getDefinitionAndBoundSpan = function (args, simplifiedResult) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
@@ -111883,18 +114597,34 @@ var ts;
textSpan: this.toLocationTextSpan(definitionAndBoundSpan.textSpan, scriptInfo)
};
}
- return definitionAndBoundSpan;
+ return __assign({}, definitionAndBoundSpan, { definitions: definitionAndBoundSpan.definitions.map(Session.mapToOriginalLocation) });
};
Session.prototype.mapDefinitionInfo = function (definitions, project) {
var _this = this;
return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); });
};
+ /*
+ * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in
+ * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols.
+ * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a
+ * set of additional fields, and does the reverse for VS (store the .d.ts location where
+ * it used to be and stores the .ts location in the additional fields).
+ */
+ Session.mapToOriginalLocation = function (def) {
+ if (def.originalFileName) {
+ ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is");
+ return __assign({}, def, { fileName: def.originalFileName, textSpan: def.originalTextSpan, targetFileName: def.fileName, targetTextSpan: def.textSpan });
+ }
+ return def;
+ };
Session.prototype.toFileSpan = function (fileName, textSpan, project) {
- var scriptInfo = project.getScriptInfo(fileName);
+ var ls = project.getLanguageService();
+ var start = ls.toLineColumnOffset(fileName, textSpan.start);
+ var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan));
return {
file: fileName,
- start: scriptInfo.positionToLineOffset(textSpan.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan))
+ start: { line: start.line + 1, offset: start.character + 1 },
+ end: { line: end.line + 1, offset: end.character + 1 }
};
};
Session.prototype.getTypeDefinition = function (args) {
@@ -111920,9 +114650,7 @@ var ts;
return _this.toFileSpan(fileName, textSpan, project);
});
}
- else {
- return implementations;
- }
+ return implementations.map(Session.mapToOriginalLocation);
};
Session.prototype.getOccurrences = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
@@ -112238,7 +114966,8 @@ var ts;
textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1),
hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1),
bannerText: s.bannerText,
- autoCollapse: s.autoCollapse
+ autoCollapse: s.autoCollapse,
+ kind: s.kind
}); });
}
else {
@@ -112394,10 +115123,10 @@ var ts;
if (simplifiedResult) {
return ts.mapDefined(completions && completions.entries, function (entry) {
if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
- var name_75 = 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 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;
// Use `hasAction || undefined` to avoid serializing `false`.
- return { name: name_75, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended };
+ 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); });
}
@@ -112783,10 +115512,16 @@ var ts;
};
Session.prototype.mapTextChangesToCodeEditsUsingScriptinfo = function (textChanges, scriptInfo) {
var _this = this;
- return {
- fileName: textChanges.fileName,
- textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); })
- };
+ ts.Debug.assert(!!textChanges.isNewFile === !scriptInfo);
+ if (scriptInfo) {
+ return {
+ fileName: textChanges.fileName,
+ textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); })
+ };
+ }
+ else {
+ return this.convertNewFileTextChangeToCodeEdit(textChanges);
+ }
};
Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) {
return {
@@ -112795,6 +115530,12 @@ var ts;
newText: change.newText ? change.newText : ""
};
};
+ Session.prototype.convertNewFileTextChangeToCodeEdit = function (textChanges) {
+ ts.Debug.assert(textChanges.textChanges.length === 1);
+ var change = ts.first(textChanges.textChanges);
+ ts.Debug.assert(change.span.start === 0 && change.span.length === 0);
+ return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] };
+ };
Session.prototype.getBraceMatching = function (args, simplifiedResult) {
var _this = this;
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
@@ -113727,5 +116468,3 @@ var ts;
}());
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-
-//# sourceMappingURL=tsserverlibrary.js.map
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index d54eff0acbd..b449fc853c6 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -337,32 +337,36 @@ declare namespace ts {
EnumMember = 272,
SourceFile = 273,
Bundle = 274,
- JSDocTypeExpression = 275,
- JSDocAllType = 276,
- JSDocUnknownType = 277,
- JSDocNullableType = 278,
- JSDocNonNullableType = 279,
- JSDocOptionalType = 280,
- JSDocFunctionType = 281,
- JSDocVariadicType = 282,
- JSDocComment = 283,
- JSDocTypeLiteral = 284,
- JSDocTag = 285,
- JSDocAugmentsTag = 286,
- JSDocClassTag = 287,
- JSDocParameterTag = 288,
- JSDocReturnTag = 289,
- JSDocTypeTag = 290,
- JSDocTemplateTag = 291,
- JSDocTypedefTag = 292,
- JSDocPropertyTag = 293,
- SyntaxList = 294,
- NotEmittedStatement = 295,
- PartiallyEmittedExpression = 296,
- CommaListExpression = 297,
- MergeDeclarationMarker = 298,
- EndOfDeclarationMarker = 299,
- Count = 300,
+ UnparsedSource = 275,
+ InputFiles = 276,
+ JSDocTypeExpression = 277,
+ JSDocAllType = 278,
+ JSDocUnknownType = 279,
+ JSDocNullableType = 280,
+ JSDocNonNullableType = 281,
+ JSDocOptionalType = 282,
+ JSDocFunctionType = 283,
+ JSDocVariadicType = 284,
+ JSDocComment = 285,
+ JSDocTypeLiteral = 286,
+ JSDocSignature = 287,
+ JSDocTag = 288,
+ JSDocAugmentsTag = 289,
+ JSDocClassTag = 290,
+ JSDocCallbackTag = 291,
+ JSDocParameterTag = 292,
+ JSDocReturnTag = 293,
+ JSDocTypeTag = 294,
+ JSDocTemplateTag = 295,
+ JSDocTypedefTag = 296,
+ JSDocPropertyTag = 297,
+ SyntaxList = 298,
+ NotEmittedStatement = 299,
+ PartiallyEmittedExpression = 300,
+ CommaListExpression = 301,
+ MergeDeclarationMarker = 302,
+ EndOfDeclarationMarker = 303,
+ Count = 304,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -388,10 +392,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 145,
- FirstJSDocNode = 275,
- LastJSDocNode = 293,
- FirstJSDocTagNode = 285,
- LastJSDocTagNode = 293
+ FirstJSDocNode = 277,
+ LastJSDocNode = 297,
+ FirstJSDocTagNode = 288,
+ LastJSDocTagNode = 297
}
enum NodeFlags {
None = 0,
@@ -415,6 +419,7 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 131072,
HasAggregatedChildData = 262144,
JSDoc = 2097152,
+ JsonFile = 16777216,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
@@ -1149,7 +1154,7 @@ declare namespace ts {
kind: SyntaxKind.NotEmittedStatement;
}
/**
- * A list of comma-seperated expressions. This node is only created by transformations.
+ * A list of comma-separated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
@@ -1277,7 +1282,7 @@ declare namespace ts {
block: Block;
}
type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode;
- type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag;
+ type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature;
interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer {
kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression;
name?: Identifier;
@@ -1534,6 +1539,19 @@ declare namespace ts {
name?: Identifier;
typeExpression?: JSDocTypeExpression | JSDocTypeLiteral;
}
+ interface JSDocCallbackTag extends JSDocTag, NamedDeclaration {
+ parent: JSDoc;
+ kind: SyntaxKind.JSDocCallbackTag;
+ fullName?: JSDocNamespaceDeclaration | Identifier;
+ name?: Identifier;
+ typeExpression: JSDocSignature;
+ }
+ interface JSDocSignature extends JSDocType, Declaration {
+ kind: SyntaxKind.JSDocSignature;
+ typeParameters?: ReadonlyArray;
+ parameters: ReadonlyArray;
+ type: JSDocReturnTag | undefined;
+ }
interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
parent: JSDoc;
name: EntityName;
@@ -1644,12 +1662,32 @@ declare namespace ts {
}
interface Bundle extends Node {
kind: SyntaxKind.Bundle;
+ prepends: ReadonlyArray;
sourceFiles: ReadonlyArray;
}
+ interface InputFiles extends Node {
+ kind: SyntaxKind.InputFiles;
+ javascriptText: string;
+ declarationText: string;
+ }
+ interface UnparsedSource extends Node {
+ kind: SyntaxKind.UnparsedSource;
+ text: string;
+ }
interface JsonSourceFile extends SourceFile {
- jsonObject?: ObjectLiteralExpression;
+ statements: NodeArray;
+ }
+ interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
}
+ interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
+ kind: SyntaxKind.PrefixUnaryExpression;
+ operator: SyntaxKind.MinusToken;
+ operand: NumericLiteral;
+ }
+ interface JsonObjectExpressionStatement extends ExpressionStatement {
+ expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
+ }
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
@@ -1705,12 +1743,19 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
+ getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
+ }
+ interface ResolvedProjectReference {
+ commandLine: ParsedCommandLine;
+ sourceFile: SourceFile;
}
interface CustomTransformers {
- /** Custom transformers to evaluate before built-in transformations. */
+ /** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory[];
- /** Custom transformers to evaluate after built-in transformations. */
+ /** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory[];
+ /** Custom transformers to evaluate after built-in .d.ts transformations. */
+ afterDeclarations?: TransformerFactory[];
}
interface SourceMapSpan {
/** Line number in the .js file. */
@@ -1853,7 +1898,9 @@ declare namespace ts {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
+ GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
+ ForbidIndexedAccessSymbolReferences = 16,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
UseOnlyExternalAliasing = 128,
@@ -2217,6 +2264,7 @@ declare namespace ts {
objectType: Type;
indexType: Type;
constraint?: Type;
+ simplified?: Type;
}
type TypeVariable = TypeParameter | IndexedAccessType;
interface IndexType extends InstantiableType {
@@ -2251,7 +2299,7 @@ declare namespace ts {
Construct = 1
}
interface Signature {
- declaration?: SignatureDeclaration;
+ declaration?: SignatureDeclaration | JSDocSignature;
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
@@ -2274,7 +2322,9 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
- interface JsFileExtensionInfo {
+ /** @deprecated Use FileExtensionInfo instead. */
+ type JsFileExtensionInfo = FileExtensionInfo;
+ interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
@@ -2322,7 +2372,17 @@ declare namespace ts {
interface PluginImport {
name: string;
}
- type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined;
+ interface ProjectReference {
+ /** A normalized path on disk */
+ path: string;
+ /** The path as the user originally wrote it */
+ originalPath?: string;
+ /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
+ prepend?: boolean;
+ /** True if it is intended that this reference form a circularity */
+ circular?: boolean;
+ }
+ type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined;
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -2378,6 +2438,7 @@ declare namespace ts {
project?: string;
reactNamespace?: string;
jsxFactory?: string;
+ composite?: boolean;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2393,11 +2454,12 @@ declare namespace ts {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
+ resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
- [option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
+ [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
interface TypeAcquisition {
enableAutoDiscovery?: boolean;
@@ -2437,7 +2499,12 @@ declare namespace ts {
TS = 3,
TSX = 4,
External = 5,
- JSON = 6
+ JSON = 6,
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ Deferred = 7
}
enum ScriptTarget {
ES3 = 0,
@@ -2447,6 +2514,7 @@ declare namespace ts {
ES2017 = 4,
ES2018 = 5,
ESNext = 6,
+ JSON = 100,
Latest = 6
}
enum LanguageVariant {
@@ -2458,6 +2526,7 @@ declare namespace ts {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
+ projectReferences?: ReadonlyArray;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike;
@@ -2469,8 +2538,17 @@ declare namespace ts {
}
interface ExpandResult {
fileNames: string[];
+ projectReferences: ReadonlyArray | undefined;
wildcardDirectories: MapLike;
}
+ interface CreateProgramOptions {
+ rootNames: ReadonlyArray;
+ options: CompilerOptions;
+ projectReferences?: ReadonlyArray;
+ host?: CompilerHost;
+ oldProgram?: Program;
+ configFileParsingDiagnostics?: ReadonlyArray;
+ }
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string | undefined;
@@ -2561,6 +2639,7 @@ declare namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
+ readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
@@ -2918,10 +2997,11 @@ declare namespace ts {
readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[];
getModifiedTime?(path: string): Date;
/**
- * This should be cryptographically secure.
* A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm)
*/
createHash?(data: string): string;
+ /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */
+ createSHA256Hash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
@@ -3298,6 +3378,8 @@ declare namespace ts {
function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag;
function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag;
function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral;
+ function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag;
+ function isJSDocSignature(node: Node): node is JSDocSignature;
}
declare namespace ts {
/**
@@ -3423,6 +3505,8 @@ declare namespace ts {
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
+ function createStringLiteral(text: string): StringLiteral;
+ function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
/** Create a unique temporary variable. */
@@ -3727,8 +3811,10 @@ declare namespace ts {
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression;
- function createBundle(sourceFiles: ReadonlyArray): Bundle;
- function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle;
+ function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
+ function createUnparsedSourceFile(text: string): UnparsedSource;
+ function createInputFiles(javascript: string, declaration: string): InputFiles;
+ function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression;
function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression;
@@ -3792,6 +3878,7 @@ declare namespace ts {
function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined;
function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T;
function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T;
+ function moveSyntheticComments(node: T, original: Node): T;
/**
* Gets the constant value to emit for an expression.
*/
@@ -3935,6 +4022,7 @@ declare namespace ts {
* @param configFileParsingDiagnostics - error during config file parsing
* @returns A 'Program' object.
*/
+ function createProgram(createProgramOptions: CreateProgramOptions): Program;
function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program;
}
declare namespace ts {
@@ -4074,7 +4162,6 @@ declare namespace ts {
function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram;
}
declare namespace ts {
- type DiagnosticReporter = (diagnostic: Diagnostic) => void;
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T;
@@ -4137,15 +4224,6 @@ declare namespace ts {
/** Compiler options */
options: CompilerOptions;
}
- /**
- * Reports config file diagnostics
- */
- interface ConfigFileDiagnosticsReporter {
- /**
- * Reports unrecoverable error when parsing config file
- */
- onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
- }
/**
* Host to create watch with config file
*/
@@ -4192,6 +4270,26 @@ declare namespace ts {
}
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine;
+ type DiagnosticReporter = (diagnostic: Diagnostic) => void;
+ /**
+ * Reports config file diagnostics
+ */
+ interface ConfigFileDiagnosticsReporter {
+ /**
+ * Reports unrecoverable error when parsing config file
+ */
+ onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
+ }
+ /**
+ * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
+ */
+ interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
+ getCurrentDirectory(): string;
+ }
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -4213,7 +4311,7 @@ declare namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
- function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile;
+ function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
/**
* Convert the json syntax tree into the json value
*/
@@ -4225,7 +4323,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
/**
* Parse the contents of a config file (tsconfig.json).
* @param jsonNode The contents of the config file to parse
@@ -4233,7 +4331,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -4252,7 +4350,7 @@ declare namespace ts {
getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number;
getFullStart(): number;
getEnd(): number;
- getWidth(sourceFile?: SourceFile): number;
+ getWidth(sourceFile?: SourceFileLike): number;
getFullWidth(): number;
getLeadingTriviaWidth(sourceFile?: SourceFile): number;
getFullText(sourceFile?: SourceFile): string;
@@ -4364,6 +4462,7 @@ declare namespace ts {
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
+ getProjectReferences?(): ReadonlyArray | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -4378,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
+ getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -4393,6 +4493,7 @@ declare namespace ts {
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
+ readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -4441,6 +4542,7 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan;
+ toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray;
getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions;
applyCodeActionCommand(action: CodeActionCommand): Promise;
@@ -4465,9 +4567,10 @@ declare namespace ts {
fileName: string;
}
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. */
- triggerCharacter?: string;
+ triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
@@ -4534,6 +4637,7 @@ declare namespace ts {
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
+ isNewFile?: boolean;
}
interface CodeAction {
/** Description of the code action to display in the UI of the editor */
@@ -4620,6 +4724,12 @@ declare namespace ts {
interface DocumentSpan {
textSpan: TextSpan;
fileName: string;
+ /**
+ * If the span represents a location that was remapped (e.g. via a .d.ts.map file),
+ * then the original filename and span will be specified here
+ */
+ originalTextSpan?: TextSpan;
+ originalFileName?: string;
}
interface RenameLocation extends DocumentSpan {
}
@@ -4717,9 +4827,7 @@ declare namespace ts {
insertSpaceBeforeTypeAnnotation?: boolean;
indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean;
}
- interface DefinitionInfo {
- fileName: string;
- textSpan: TextSpan;
+ interface DefinitionInfo extends DocumentSpan {
kind: ScriptElementKind;
name: string;
containerKind: ScriptElementKind;
@@ -4865,6 +4973,20 @@ declare namespace ts {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
+ /**
+ * Classification of the contents of the span
+ */
+ kind: OutliningSpanKind;
+ }
+ enum OutliningSpanKind {
+ /** Single or multi-line comments */
+ Comment = "comment",
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ Region = "region",
+ /** Declarations and expressions */
+ Code = "code",
+ /** Contiguous blocks of import declarations */
+ Imports = "imports"
}
enum OutputFileType {
JavaScript = 0,
@@ -4988,7 +5110,9 @@ declare namespace ts {
/**
*
*/
- jsxAttribute = "JSX attribute"
+ jsxAttribute = "JSX attribute",
+ /** String literal */
+ string = "string"
}
enum ScriptElementKindModifier {
none = "",
diff --git a/lib/typescript.js b/lib/typescript.js
index 86c2e32ef0e..5a20323ef59 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -350,38 +350,42 @@ var ts;
// Top-level nodes
SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile";
SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 287] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 288] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 289] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 290] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 291] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 292] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 293] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 294] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 295] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 296] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 297] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 298] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 299] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 300] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 301] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 302] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 303] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 300] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 304] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
@@ -408,10 +412,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 297] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 288] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 297] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -451,6 +455,7 @@ var ts;
NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
/* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
/* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
+ NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile";
NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
@@ -513,10 +518,9 @@ var ts;
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
// Flags
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
/* @internal */
var TokenFlags;
@@ -591,9 +595,9 @@ var ts;
// Options
NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- // empty space
+ NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
- // empty space
+ NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
@@ -885,6 +889,8 @@ var ts;
TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType";
TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive";
/* @internal */
+ TypeFlags[TypeFlags["UnionOfUnitTypes"] = 268435456] = "UnionOfUnitTypes";
+ /* @internal */
TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable";
@@ -920,6 +926,8 @@ var ts;
TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit";
/* @internal */
+ TypeFlags[TypeFlags["NotUnit"] = 8374815] = "NotUnit";
+ /* @internal */
TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening";
/* @internal */
TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags";
@@ -1072,6 +1080,11 @@ var ts;
ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
ScriptKind[ScriptKind["External"] = 5] = "External";
ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
})(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
var ScriptTarget;
(function (ScriptTarget) {
@@ -1082,6 +1095,7 @@ var ts;
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
@@ -1894,8 +1908,8 @@ var ts;
}
ts.findLast = findLast;
/** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
- function findIndex(array, predicate) {
- for (var i = 0; i < array.length; i++) {
+ function findIndex(array, predicate, startIndex) {
+ for (var i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
@@ -1903,6 +1917,15 @@ var ts;
return -1;
}
ts.findIndex = findIndex;
+ function findLastIndex(array, predicate, startIndex) {
+ for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
+ if (predicate(array[i], i)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ ts.findLastIndex = findLastIndex;
/**
* Returns the first truthy result of `callback`, or else fails.
* This is like `forEach`, but never returns undefined.
@@ -2255,6 +2278,24 @@ var ts;
return false;
}
ts.some = some;
+ /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
+ function getRangesWhere(arr, pred, cb) {
+ var start;
+ for (var i = 0; i < arr.length; i++) {
+ if (pred(arr[i])) {
+ start = start === undefined ? i : start;
+ }
+ else {
+ if (start !== undefined) {
+ cb(start, i);
+ start = undefined;
+ }
+ }
+ }
+ if (start !== undefined)
+ cb(start, arr.length);
+ }
+ ts.getRangesWhere = getRangesWhere;
function concatenate(array1, array2) {
if (!some(array2))
return array1;
@@ -2498,6 +2539,23 @@ var ts;
return to;
}
ts.addRange = addRange;
+ /**
+ * Appends a range of value to begin of an array, returning the array.
+ *
+ * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array
+ * is created if `value` was appended.
+ * @param from The values to append to the array. If `from` is `undefined`, nothing is
+ * appended. If an element of `from` is `undefined`, that element is not appended.
+ */
+ function prependRange(to, from) {
+ if (from === undefined || from.length === 0)
+ return to;
+ if (to === undefined)
+ return from.slice();
+ to.unshift.apply(to, from);
+ return to;
+ }
+ ts.prependRange = prependRange;
/**
* @return Whether the value was added.
*/
@@ -2747,17 +2805,18 @@ var ts;
}
ts.getOwnValues = getOwnValues;
function arrayFrom(iterator, map) {
+ var _a;
var result = [];
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
result.push(map ? map(value) : value);
}
return result;
- var _b;
}
ts.arrayFrom = arrayFrom;
function forEachEntry(map, callback) {
+ var _a;
var iterator = map.entries();
- for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
var key = pair[0], value = pair[1];
var result = callback(value, key);
if (result) {
@@ -2765,19 +2824,18 @@ var ts;
}
}
return undefined;
- var _b;
}
ts.forEachEntry = forEachEntry;
function forEachKey(map, callback) {
+ var _a;
var iterator = map.keys();
- for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
var result = callback(key);
if (result) {
return result;
}
}
return undefined;
- var _b;
}
ts.forEachKey = forEachKey;
function copyEntries(source, target) {
@@ -3334,11 +3392,11 @@ var ts;
comparer(a[key], b[key]);
}
ts.compareProperties = compareProperties;
- function getDiagnosticFileName(diagnostic) {
- return diagnostic.file ? diagnostic.file.fileName : undefined;
+ function getDiagnosticFilePath(diagnostic) {
+ return diagnostic.file ? diagnostic.file.path : undefined;
}
function compareDiagnostics(d1, d2) {
- return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
+ return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
@@ -3370,106 +3428,6 @@ var ts;
// We still have one chain remaining. The shorter chain should come first.
return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */;
}
- function normalizeSlashes(path) {
- return path.replace(/\\/g, "/");
- }
- ts.normalizeSlashes = normalizeSlashes;
- /**
- * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
- */
- function getRootLength(path) {
- if (path.charCodeAt(0) === 47 /* slash */) {
- if (path.charCodeAt(1) !== 47 /* slash */)
- return 1;
- var p1 = path.indexOf("/", 2);
- if (p1 < 0)
- return 2;
- var p2 = path.indexOf("/", p1 + 1);
- if (p2 < 0)
- return p1 + 1;
- return p2 + 1;
- }
- if (path.charCodeAt(1) === 58 /* colon */) {
- if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */)
- return 3;
- }
- // Per RFC 1738 'file' URI schema has the shape file:///
- // if is omitted then it is assumed that host value is 'localhost',
- // however slash after the omitted is not removed.
- // file:///folder1/file1 - this is a correct URI
- // file://folder2/file2 - this is an incorrect URI
- if (path.lastIndexOf("file:///", 0) === 0) {
- return "file:///".length;
- }
- var idx = path.indexOf("://");
- if (idx !== -1) {
- return idx + "://".length;
- }
- return 0;
- }
- ts.getRootLength = getRootLength;
- /**
- * Internally, we represent paths as strings with '/' as the directory separator.
- * When we make system calls (eg: LanguageServiceHost.getDirectory()),
- * we expect the host to correctly handle paths in our specified format.
- */
- ts.directorySeparator = "/";
- var directorySeparatorCharCode = 47 /* slash */;
- function getNormalizedParts(normalizedSlashedPath, rootLength) {
- var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator);
- var normalized = [];
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
- var part = parts_1[_i];
- if (part !== ".") {
- if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") {
- normalized.pop();
- }
- else {
- // A part may be an empty string (which is 'falsy') if the path had consecutive slashes,
- // e.g. "path//file.ts". Drop these before re-joining the parts.
- if (part) {
- normalized.push(part);
- }
- }
- }
- }
- return normalized;
- }
- function normalizePath(path) {
- return normalizePathAndParts(path).path;
- }
- ts.normalizePath = normalizePath;
- function normalizePathAndParts(path) {
- path = normalizeSlashes(path);
- var rootLength = getRootLength(path);
- var root = path.substr(0, rootLength);
- var parts = getNormalizedParts(path, rootLength);
- if (parts.length) {
- var joinedParts = root + parts.join(ts.directorySeparator);
- return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts };
- }
- else {
- return { path: root, parts: parts };
- }
- }
- ts.normalizePathAndParts = normalizePathAndParts;
- /** A path ending with '/' refers to a directory only, never a file. */
- function pathEndsWithDirectorySeparator(path) {
- return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
- }
- ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator;
- function getDirectoryPath(path) {
- return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator)));
- }
- ts.getDirectoryPath = getDirectoryPath;
- function isUrl(path) {
- return path && !isRootedDiskPath(path) && stringContains(path, "://");
- }
- ts.isUrl = isUrl;
- function pathIsRelative(path) {
- return /^\.\.?($|[\\/])/.test(path);
- }
- ts.pathIsRelative = pathIsRelative;
function getEmitScriptTarget(compilerOptions) {
return compilerOptions.target || 0 /* ES3 */;
}
@@ -3501,6 +3459,10 @@ var ts;
: moduleKind === ts.ModuleKind.System;
}
ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
+ function getEmitDeclarations(compilerOptions) {
+ return !!(compilerOptions.declaration || compilerOptions.composite);
+ }
+ ts.getEmitDeclarations = getEmitDeclarations;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
}
@@ -3521,202 +3483,455 @@ var ts;
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ //
+ // Paths
+ //
+ /**
+ * Internally, we represent paths as strings with '/' as the directory separator.
+ * When we make system calls (eg: LanguageServiceHost.getDirectory()),
+ * we expect the host to correctly handle paths in our specified format.
+ */
+ ts.directorySeparator = "/";
+ var altDirectorySeparator = "\\";
+ var urlSchemeSeparator = "://";
+ var backslashRegExp = /\\/g;
+ /**
+ * Normalize path separators.
+ */
+ function normalizeSlashes(path) {
+ return path.replace(backslashRegExp, ts.directorySeparator);
+ }
+ ts.normalizeSlashes = normalizeSlashes;
+ function isVolumeCharacter(charCode) {
+ return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
+ (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
+ }
+ function getFileUrlVolumeSeparatorEnd(url, start) {
+ var ch0 = url.charCodeAt(start);
+ if (ch0 === 58 /* colon */)
+ return start + 1;
+ if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
+ var ch2 = url.charCodeAt(start + 2);
+ if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
+ return start + 3;
+ }
+ return -1;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ * If the root is part of a URL, the twos-complement of the root length is returned.
+ */
+ function getEncodedRootLength(path) {
+ if (!path)
+ return 0;
+ var ch0 = path.charCodeAt(0);
+ // POSIX or UNC
+ if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
+ if (path.charCodeAt(1) !== ch0)
+ return 1; // POSIX: "/" (or non-normalized "\")
+ var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
+ if (p1 < 0)
+ return path.length; // UNC: "//server" or "\\server"
+ return p1 + 1; // UNC: "//server/" or "\\server\"
+ }
+ // DOS
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
+ var ch2 = path.charCodeAt(2);
+ if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
+ return 3; // DOS: "c:/" or "c:\"
+ if (path.length === 2)
+ return 2; // DOS: "c:" (but not "c:d")
+ }
+ // URL
+ var schemeEnd = path.indexOf(urlSchemeSeparator);
+ if (schemeEnd !== -1) {
+ var authorityStart = schemeEnd + urlSchemeSeparator.length;
+ var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
+ if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
+ // For local "file" URLs, include the leading DOS volume (if present).
+ // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
+ // special case interpreted as "the machine from which the URL is being interpreted".
+ var scheme = path.slice(0, schemeEnd);
+ var authority = path.slice(authorityStart, authorityEnd);
+ if (scheme === "file" && (authority === "" || authority === "localhost") &&
+ isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
+ var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
+ if (volumeSeparatorEnd !== -1) {
+ if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
+ // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
+ return ~(volumeSeparatorEnd + 1);
+ }
+ if (volumeSeparatorEnd === path.length) {
+ // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
+ // but not "file:///c:d" or "file:///c%3ad"
+ return ~volumeSeparatorEnd;
+ }
+ }
+ }
+ return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
+ }
+ return ~path.length; // URL: "file://server", "http://server"
+ }
+ // relative
+ return 0;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ *
+ * For example:
+ * ```ts
+ * getRootLength("a") === 0 // ""
+ * getRootLength("/") === 1 // "/"
+ * getRootLength("c:") === 2 // "c:"
+ * getRootLength("c:d") === 0 // ""
+ * getRootLength("c:/") === 3 // "c:/"
+ * getRootLength("c:\\") === 3 // "c:\\"
+ * getRootLength("//server") === 7 // "//server"
+ * getRootLength("//server/share") === 8 // "//server/"
+ * getRootLength("\\\\server") === 7 // "\\\\server"
+ * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
+ * getRootLength("file:///path") === 8 // "file:///"
+ * getRootLength("file:///c:") === 10 // "file:///c:"
+ * getRootLength("file:///c:d") === 8 // "file:///"
+ * getRootLength("file:///c:/path") === 11 // "file:///c:/"
+ * getRootLength("file://server") === 13 // "file://server"
+ * getRootLength("file://server/path") === 14 // "file://server/"
+ * getRootLength("http://server") === 13 // "http://server"
+ * getRootLength("http://server/path") === 14 // "http://server/"
+ * ```
+ */
+ function getRootLength(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength < 0 ? ~rootLength : rootLength;
+ }
+ ts.getRootLength = getRootLength;
+ // TODO(rbuckton): replace references with `resolvePath`
+ function normalizePath(path) {
+ return resolvePath(path);
+ }
+ ts.normalizePath = normalizePath;
+ function normalizePathAndParts(path) {
+ path = normalizeSlashes(path);
+ var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
+ if (parts.length) {
+ var joinedParts = root + parts.join(ts.directorySeparator);
+ return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
+ }
+ else {
+ return { path: root, parts: parts };
+ }
+ }
+ ts.normalizePathAndParts = normalizePathAndParts;
+ function getDirectoryPath(path) {
+ path = normalizeSlashes(path);
+ // If the path provided is itself the root, then return it.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return path;
+ // return the leading portion of the path up to the last (non-terminal) directory separator
+ // but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
+ }
+ ts.getDirectoryPath = getDirectoryPath;
+ function isUrl(path) {
+ return getEncodedRootLength(path) < 0;
+ }
+ ts.isUrl = isUrl;
+ function pathIsRelative(path) {
+ return /^\.\.?($|[\\/])/.test(path);
+ }
+ ts.pathIsRelative = pathIsRelative;
+ /**
+ * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
+ * like `c:`, `c:\` or `c:/`).
+ */
function isRootedDiskPath(path) {
- return path && getRootLength(path) !== 0;
+ return getEncodedRootLength(path) > 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
+ /**
+ * Determines whether a path consists only of a path root.
+ */
+ function isDiskPathRoot(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength > 0 && rootLength === path.length;
+ }
+ ts.isDiskPathRoot = isDiskPathRoot;
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
ts.convertToRelativePath = convertToRelativePath;
- function normalizedPathComponents(path, rootLength) {
- var normalizedParts = getNormalizedParts(path, rootLength);
- return [path.substr(0, rootLength)].concat(normalizedParts);
+ function pathComponents(path, rootLength) {
+ var root = path.substring(0, rootLength);
+ var rest = path.substring(rootLength).split(ts.directorySeparator);
+ if (rest.length && !lastOrUndefined(rest))
+ rest.pop();
+ return [root].concat(rest);
}
- function getNormalizedPathComponents(path, currentDirectory) {
- path = normalizeSlashes(path);
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is not normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getPathComponents(path, currentDirectory) {
+ if (currentDirectory === void 0) { currentDirectory = ""; }
+ path = combinePaths(currentDirectory, path);
var rootLength = getRootLength(path);
- if (rootLength === 0) {
- // If the path is not rooted it is relative to current directory
- path = combinePaths(normalizeSlashes(currentDirectory), path);
- rootLength = getRootLength(path);
+ return pathComponents(path, rootLength);
+ }
+ ts.getPathComponents = getPathComponents;
+ /**
+ * Reduce an array of path components to a more simplified path by navigating any
+ * `"."` or `".."` entries in the path.
+ */
+ function reducePathComponents(components) {
+ if (!some(components))
+ return [];
+ var reduced = [components[0]];
+ for (var i = 1; i < components.length; i++) {
+ var component = components[i];
+ if (!component)
+ continue;
+ if (component === ".")
+ continue;
+ if (component === "..") {
+ if (reduced.length > 1) {
+ if (reduced[reduced.length - 1] !== "..") {
+ reduced.pop();
+ continue;
+ }
+ }
+ else if (reduced[0])
+ continue;
+ }
+ reduced.push(component);
}
- return normalizedPathComponents(path, rootLength);
+ return reduced;
+ }
+ ts.reducePathComponents = reducePathComponents;
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getNormalizedPathComponents(path, currentDirectory) {
+ return reducePathComponents(getPathComponents(path, currentDirectory));
}
ts.getNormalizedPathComponents = getNormalizedPathComponents;
function getNormalizedAbsolutePath(fileName, currentDirectory) {
- return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
+ return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
- function getNormalizedPathFromPathComponents(pathComponents) {
- if (pathComponents && pathComponents.length) {
- return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator);
- }
+ /**
+ * Formats a parsed path consisting of a root component (at index 0) and zero or more path
+ * segments (at indices > 0).
+ */
+ function getPathFromPathComponents(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
+ if (pathComponents.length === 1)
+ return root;
+ return root + pathComponents.slice(1).join(ts.directorySeparator);
}
- ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents;
- function getNormalizedPathComponentsOfUrl(url) {
- // Get root length of http://www.website.com/folder1/folder2/
- // In this example the root is: http://www.website.com/
- // normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
- var urlLength = url.length;
- // Initial root length is http:// part
- var rootLength = url.indexOf("://") + "://".length;
- while (rootLength < urlLength) {
- // Consume all immediate slashes in the protocol
- // eg.initial rootlength is just file:// but it needs to consume another "/" in file:///
- if (url.charCodeAt(rootLength) === 47 /* slash */) {
- rootLength++;
- }
- else {
- // non slash character means we continue proceeding to next component of root search
+ ts.getPathFromPathComponents = getPathFromPathComponents;
+ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
+ var fromComponents = reducePathComponents(getPathComponents(from));
+ var toComponents = reducePathComponents(getPathComponents(to));
+ var start;
+ for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
+ var fromComponent = getCanonicalFileName(fromComponents[start]);
+ var toComponent = getCanonicalFileName(toComponents[start]);
+ var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
+ if (!comparer(fromComponent, toComponent))
break;
- }
}
- // there are no parts after http:// just return current string as the pathComponent
- if (rootLength === urlLength) {
- return [url];
+ if (start === 0) {
+ return toComponents;
}
- // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://)
- var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength);
- if (indexOfNextSlash !== -1) {
- // Found the "/" after the website.com so the root is length of http://www.website.com/
- // and get components after the root normally like any other folder components
- rootLength = indexOfNextSlash + 1;
- return normalizedPathComponents(url, rootLength);
- }
- else {
- // Can't find the host assume the rest of the string as component
- // but make sure we append "/" to it as root is not joined using "/"
- // eg. if url passed in was http://website.com we want to use root as [http://website.com/]
- // so that other path manipulations will be correct and it can be merged with relative paths correctly
- return [url + ts.directorySeparator];
+ var components = toComponents.slice(start);
+ var relative = [];
+ for (; start < fromComponents.length; start++) {
+ relative.push("..");
}
+ return [""].concat(relative, components);
}
- function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) {
- if (isUrl(pathOrUrl)) {
- return getNormalizedPathComponentsOfUrl(pathOrUrl);
- }
- else {
- return getNormalizedPathComponents(pathOrUrl, currentDirectory);
- }
+ function getRelativePathFromFile(from, to, getCanonicalFileName) {
+ return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
+ ts.getRelativePathFromFile = getRelativePathFromFile;
+ function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
+ Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
+ var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
+ var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
+ var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
- var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
- var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
- if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
- // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name
- // that is ["test", "cases", ""] needs to be actually ["test", "cases"]
- directoryComponents.pop();
+ var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName);
+ var firstComponent = pathComponents[0];
+ if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
+ var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
+ pathComponents[0] = prefix + firstComponent;
}
- // Find the component that differs
- var joinStartIndex;
- for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
- break;
- }
- }
- // Get the relative path
- if (joinStartIndex) {
- var relativePath = "";
- var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length);
- for (; joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (directoryComponents[joinStartIndex] !== "") {
- relativePath = relativePath + ".." + ts.directorySeparator;
- }
- }
- return relativePath + relativePathComponents.join(ts.directorySeparator);
- }
- // Cant find the relative path, get the absolute path
- var absolutePath = getNormalizedPathFromPathComponents(pathComponents);
- if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) {
- absolutePath = "file:///" + absolutePath;
- }
- return absolutePath;
+ return getPathFromPathComponents(pathComponents);
}
ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
- function getRelativePath(path, directoryPath, getCanonicalFileName) {
- var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ensurePathIsRelative(relativePath);
+ /**
+ * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
+ * with `./` or `../`) so as not to be confused with an unprefixed module name.
+ */
+ function ensurePathIsNonModuleName(path) {
+ return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path;
}
- ts.getRelativePath = getRelativePath;
- function ensurePathIsRelative(path) {
- return !pathIsRelative(path) ? "./" + path : path;
- }
- ts.ensurePathIsRelative = ensurePathIsRelative;
- function getBaseFileName(path) {
- if (path === undefined) {
- return undefined;
- }
- var i = path.lastIndexOf(ts.directorySeparator);
- return i < 0 ? path : path.substring(i + 1);
+ ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
+ function getBaseFileName(path, extensions, ignoreCase) {
+ path = normalizeSlashes(path);
+ // if the path provided is itself the root, then it has not file name.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return "";
+ // return the trailing portion of the path starting after the last (non-terminal) directory
+ // separator but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
+ var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
+ return extension ? name.slice(0, name.length - extension.length) : name;
}
ts.getBaseFileName = getBaseFileName;
- function combinePaths(path1, path2) {
- if (!(path1 && path1.length))
- return path2;
- if (!(path2 && path2.length))
- return path1;
- if (getRootLength(path2) !== 0)
- return path2;
- if (path1.charAt(path1.length - 1) === ts.directorySeparator)
- return path1 + path2;
- return path1 + ts.directorySeparator + path2;
+ /**
+ * Combines paths. If a path is absolute, it replaces any previous path.
+ */
+ function combinePaths(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ if (path)
+ path = normalizeSlashes(path);
+ for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
+ var relativePath = paths_1[_a];
+ if (!relativePath)
+ continue;
+ relativePath = normalizeSlashes(relativePath);
+ if (!path || getRootLength(relativePath) !== 0) {
+ path = relativePath;
+ }
+ else {
+ path = ensureTrailingDirectorySeparator(path) + relativePath;
+ }
+ }
+ return path;
}
ts.combinePaths = combinePaths;
+ /**
+ * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
+ * `.` and `..` path components are resolved.
+ */
+ function resolvePath(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path);
+ var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
+ return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
+ }
+ ts.resolvePath = resolvePath;
+ /**
+ * Determines whether a path has a trailing separator (`/` or `\\`).
+ */
+ function hasTrailingDirectorySeparator(path) {
+ if (path.length === 0)
+ return false;
+ var ch = path.charCodeAt(path.length - 1);
+ return ch === 47 /* slash */ || ch === 92 /* backslash */;
+ }
+ ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function removeTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) === ts.directorySeparator) {
+ if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
function ensureTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) !== ts.directorySeparator) {
+ if (!hasTrailingDirectorySeparator(path)) {
return path + ts.directorySeparator;
}
return path;
}
ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
- function comparePaths(a, b, currentDirectory, ignoreCase) {
+ function comparePathsWorker(a, b, componentComparer) {
if (a === b)
return 0 /* EqualTo */;
if (a === undefined)
return -1 /* LessThan */;
if (b === undefined)
return 1 /* GreaterThan */;
- a = removeTrailingDirectorySeparator(a);
- b = removeTrailingDirectorySeparator(b);
- var aComponents = getNormalizedPathComponents(a, currentDirectory);
- var bComponents = getNormalizedPathComponents(b, currentDirectory);
+ var aComponents = reducePathComponents(getPathComponents(a));
+ var bComponents = reducePathComponents(getPathComponents(b));
var sharedLength = Math.min(aComponents.length, bComponents.length);
- var comparer = getStringComparer(ignoreCase);
for (var i = 0; i < sharedLength; i++) {
- var result = comparer(aComponents[i], bComponents[i]);
+ var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer;
+ var result = stringComparer(aComponents[i], bComponents[i]);
if (result !== 0 /* EqualTo */) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
+ /**
+ * Performs a case-sensitive comparison of two paths.
+ */
+ function comparePathsCaseSensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseSensitive);
+ }
+ ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ /**
+ * Performs a case-insensitive comparison of two paths.
+ */
+ function comparePathsCaseInsensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseInsensitive);
+ }
+ ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
+ function comparePaths(a, b, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ a = combinePaths(currentDirectory, a);
+ b = combinePaths(currentDirectory, b);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
+ return comparePathsWorker(a, b, getStringComparer(ignoreCase));
+ }
ts.comparePaths = comparePaths;
function containsPath(parent, child, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ parent = combinePaths(currentDirectory, parent);
+ child = combinePaths(currentDirectory, child);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
if (parent === undefined || child === undefined)
return false;
if (parent === child)
return true;
- parent = removeTrailingDirectorySeparator(parent);
- child = removeTrailingDirectorySeparator(child);
- if (parent === child)
- return true;
- var parentComponents = getNormalizedPathComponents(parent, currentDirectory);
- var childComponents = getNormalizedPathComponents(child, currentDirectory);
+ var parentComponents = reducePathComponents(getPathComponents(parent));
+ var childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
- var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
+ var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (var i = 0; i < parentComponents.length; i++) {
+ var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
@@ -4050,13 +4265,17 @@ var ts;
ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
- var needAllExtensions = options && options.allowJs;
- if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
- return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ var needJsExtensions = options && options.allowJs;
+ if (!extraFileExtensions || extraFileExtensions.length === 0) {
+ return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
- return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive);
+ var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
+ return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
+ function isJavaScriptLike(scriptKind) {
+ return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
+ }
function hasJavaScriptFileExtension(fileName) {
return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}
@@ -4128,7 +4347,7 @@ var ts;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */];
+ var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
@@ -4149,9 +4368,14 @@ var ts;
}
ts.removeExtension = removeExtension;
function changeExtension(path, newExtension) {
- return (removeFileExtension(path) + newExtension);
+ return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
}
ts.changeExtension = changeExtension;
+ function changeAnyExtension(path, ext, extensions, ignoreCase) {
+ var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
+ return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
+ }
+ ts.changeAnyExtension = changeAnyExtension;
/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*/
@@ -4437,6 +4661,10 @@ var ts;
return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
}
ts.extensionIsTypeScript = extensionIsTypeScript;
+ function resolutionExtensionIsTypeScriptOrJson(ext) {
+ return extensionIsTypeScript(ext) || ext === ".json" /* Json */;
+ }
+ ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson;
/**
* Gets the extension from a path.
* Path must have a valid extension.
@@ -4457,14 +4685,34 @@ var ts;
return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); });
}
ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
- // Retrieves any string from the final "." onwards from a base file name.
- // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
- function getAnyExtensionFromPath(path) {
+ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
+ if (typeof extensions === "string")
+ extensions = [extensions];
+ for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
+ var extension = extensions_2[_i];
+ if (!startsWith(extension, "."))
+ extension = "." + extension;
+ if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
+ var pathExtension = path.slice(path.length - extension.length);
+ if (stringEqualityComparer(pathExtension, extension)) {
+ return pathExtension;
+ }
+ }
+ }
+ return "";
+ }
+ function getAnyExtensionFromPath(path, extensions, ignoreCase) {
+ // Retrieves any string from the final "." onwards from a base file name.
+ // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
+ if (extensions) {
+ return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
+ }
var baseFileName = getBaseFileName(path);
var extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
+ return "";
}
ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
@@ -4566,12 +4814,12 @@ var ts;
/* @internal */
ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
function createPollingIntervalBasedLevels(levels) {
+ var _a;
return _a = {},
_a[PollingInterval.Low] = levels.Low,
_a[PollingInterval.Medium] = levels.Medium,
_a[PollingInterval.High] = levels.High,
_a;
- var _a;
}
var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
@@ -4936,6 +5184,7 @@ var ts;
readDirectory: readDirectory,
getModifiedTime: getModifiedTime,
createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
global.gc();
@@ -5374,6 +5623,11 @@ var ts;
hash.update(data);
return hash.digest("hex");
}
+ function createSHA256Hash(data) {
+ var hash = _crypto.createHash("sha256");
+ hash.update(data);
+ return hash.digest("hex");
+ }
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -5685,7 +5939,7 @@ var ts;
Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
- Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."),
+ Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
@@ -6162,6 +6416,7 @@ var ts;
Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
+ Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
@@ -6345,6 +6600,17 @@ var ts;
Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
_0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
+ Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
+ All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
+ Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
+ Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
+ Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
+ Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
+ Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
+ Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
+ File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
+ Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
+ Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
@@ -6443,6 +6709,7 @@ var ts;
Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
+ Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
@@ -6506,6 +6773,12 @@ var ts;
Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
+ Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
+ Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
+ Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
+ Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
+ Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
+ Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -8256,11 +8529,10 @@ var ts;
}
}
function scanJSDocToken() {
+ startPos = tokenPos = pos;
if (pos >= end) {
return token = 1 /* EndOfFileToken */;
}
- startPos = pos;
- tokenPos = pos;
var ch = text.charCodeAt(pos);
pos++;
switch (ch) {
@@ -8666,7 +8938,7 @@ var ts;
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 294 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 298 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8868,12 +9140,12 @@ var ts;
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 154 /* Constructor */:
@@ -8881,6 +9153,9 @@ var ts;
case 156 /* SetAccessor */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 287 /* JSDocSignature */:
return true;
default:
ts.assertTypeIsNever(node);
@@ -8903,6 +9178,12 @@ var ts;
case 243 /* ImportDeclaration */:
case 242 /* ImportEqualsDeclaration */:
case 213 /* VariableStatement */:
+ case 234 /* ClassDeclaration */:
+ case 233 /* FunctionDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 237 /* EnumDeclaration */:
return true;
default:
return false;
@@ -8916,13 +9197,7 @@ var ts;
// Gets the nearest enclosing block scope container that has the provided node
// as a descendant, that is not the provided node.
function getEnclosingBlockScopeContainer(node) {
- var current = node.parent;
- while (current) {
- if (isBlockScope(current, current.parent)) {
- return current;
- }
- current = current.parent;
- }
+ return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
}
ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
// Return display name of an identifier
@@ -9040,6 +9315,8 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 236 /* TypeAliasDeclaration */:
+ case 151 /* PropertyDeclaration */:
+ case 150 /* PropertySignature */:
errorNode = node.name;
break;
case 192 /* ArrowFunction */:
@@ -9070,6 +9347,10 @@ var ts;
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
+ function isJsonSourceFile(file) {
+ return file.scriptKind === 6 /* JSON */;
+ }
+ ts.isJsonSourceFile = isJsonSourceFile;
function isConstEnumDeclaration(node) {
return node.kind === 237 /* EnumDeclaration */ && isConst(node);
}
@@ -9409,6 +9690,23 @@ var ts;
});
}
ts.getPropertyAssignment = getPropertyAssignment;
+ function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
+ if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
+ var expression = tsConfigSourceFile.statements[0].expression;
+ return ts.isObjectLiteralExpression(expression) && expression;
+ }
+ }
+ ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
+ function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
+ var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
+ return jsonObjectLiteral &&
+ ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
function getContainingFunction(node) {
return ts.findAncestor(node.parent, ts.isFunctionLike);
}
@@ -9786,6 +10084,10 @@ var ts;
return node && !!(node.flags & 65536 /* JavaScriptFile */);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isInJsonFile(node) {
+ return node && !!(node.flags & 16777216 /* JsonFile */);
+ }
+ ts.isInJsonFile = isInJsonFile;
function isInJSDoc(node) {
return node && !!(node.flags & 2097152 /* JSDoc */);
}
@@ -10010,6 +10312,10 @@ var ts;
}
ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
function importFromModuleSpecifier(node) {
+ return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
+ }
+ ts.importFromModuleSpecifier = importFromModuleSpecifier;
+ function tryGetImportFromModuleSpecifier(node) {
switch (node.parent.kind) {
case 243 /* ImportDeclaration */:
case 249 /* ExportDeclaration */:
@@ -10019,12 +10325,13 @@ var ts;
case 186 /* CallExpression */:
return node.parent;
case 177 /* LiteralType */:
- return ts.cast(node.parent.parent, ts.isImportTypeNode);
+ ts.Debug.assert(ts.isStringLiteral(node));
+ return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
default:
- return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
+ return undefined;
}
}
- ts.importFromModuleSpecifier = importFromModuleSpecifier;
+ ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
function getExternalModuleName(node) {
switch (node.kind) {
case 243 /* ImportDeclaration */:
@@ -10073,12 +10380,20 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 281 /* JSDocFunctionType */ &&
+ return node.kind === 283 /* JSDocFunctionType */ &&
node.parameters.length > 0 &&
node.parameters[0].name &&
node.parameters[0].name.escapedText === "new";
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
+ function isJSDocTypeAlias(node) {
+ return node.kind === 296 /* JSDocTypedefTag */ || node.kind === 291 /* JSDocCallbackTag */;
+ }
+ ts.isJSDocTypeAlias = isJSDocTypeAlias;
+ function isTypeAlias(node) {
+ return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
+ }
+ ts.isTypeAlias = isTypeAlias;
function getSourceOfAssignment(node) {
return ts.isExpressionStatement(node) &&
node.expression && ts.isBinaryExpression(node.expression) &&
@@ -10100,6 +10415,8 @@ var ts;
return v && v.initializer;
case 151 /* PropertyDeclaration */:
return node.initializer;
+ case 269 /* PropertyAssignment */:
+ return node.initializer;
}
}
function getSingleVariableOfVariableStatement(node) {
@@ -10113,9 +10430,9 @@ var ts;
node.body.kind === 238 /* ModuleDeclaration */ &&
node.body;
}
- function getJSDocCommentsAndTags(node) {
+ function getJSDocCommentsAndTags(hostNode) {
var result;
- getJSDocCommentsAndTagsWorker(node);
+ getJSDocCommentsAndTagsWorker(hostNode);
return result || ts.emptyArray;
function getJSDocCommentsAndTagsWorker(node) {
var parent = node.parent;
@@ -10130,8 +10447,7 @@ var ts;
// * @returns {number}
// */
// var x = function(name) { return name.length; }
- if (parent.parent &&
- (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) {
+ if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) {
getJSDocCommentsAndTagsWorker(parent.parent);
}
if (parent.parent && parent.parent.parent &&
@@ -10140,8 +10456,8 @@ var ts;
getSourceOfDefaultedAssignment(parent.parent.parent))) {
getJSDocCommentsAndTagsWorker(parent.parent.parent);
}
- if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ ||
- ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 /* None */ ||
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */ ||
+ ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */ ||
node.kind === 184 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 215 /* ExpressionStatement */) {
getJSDocCommentsAndTagsWorker(parent);
}
@@ -10149,7 +10465,7 @@ var ts;
if (node.kind === 148 /* Parameter */) {
result = ts.addRange(result, ts.getJSDocParameterTags(node));
}
- if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) {
+ if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) {
result = ts.addRange(result, node.initializer.jsDoc);
}
if (ts.hasJSDocNodes(node)) {
@@ -10176,7 +10492,10 @@ var ts;
}
ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
function getHostSignatureFromJSDoc(node) {
- var host = getJSDocHost(node);
+ return getHostSignatureFromJSDocHost(getJSDocHost(node));
+ }
+ ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
+ function getHostSignatureFromJSDocHost(host) {
var decl = getSourceOfDefaultedAssignment(host) ||
getSourceOfAssignment(host) ||
getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
@@ -10185,19 +10504,9 @@ var ts;
host;
return decl && ts.isFunctionLike(decl) ? decl : undefined;
}
- ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
+ ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
- while (node.parent.kind === 284 /* JSDocTypeLiteral */) {
- if (node.parent.parent.kind === 292 /* JSDocTypedefTag */) {
- node = node.parent.parent;
- }
- else {
- // node.parent.parent is a type expression, child of a parameter type
- node = node.parent.parent.parent;
- }
- }
- ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */);
- return node.parent.parent;
+ return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -10212,7 +10521,8 @@ var ts;
}
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
- return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282 /* JSDocVariadicType */;
+ var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
+ return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10354,8 +10664,14 @@ var ts;
if (ts.isDeclaration(name.parent)) {
return name.parent.name === name;
}
- var binExp = name.parent.parent;
- return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ else if (ts.isQualifiedName(name.parent)) {
+ var tag = name.parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === name.parent;
+ }
+ else {
+ var binExp = name.parent.parent;
+ return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ }
default:
return false;
}
@@ -10735,7 +11051,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
return 0;
case 203 /* SpreadElement */:
return 1;
@@ -11064,8 +11380,8 @@ var ts;
};
}
ts.createTextWriter = createTextWriter;
- function getResolvedExternalModuleName(host, file) {
- return file.moduleName || getExternalModuleNameFromPath(host, file.fileName);
+ function getResolvedExternalModuleName(host, file, referenceFile) {
+ return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
}
ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
@@ -11079,12 +11395,13 @@ var ts;
/**
* Resolves a local path to a path which is absolute to the base of the emit
*/
- function getExternalModuleNameFromPath(host, fileName) {
+ function getExternalModuleNameFromPath(host, fileName, referencePath) {
var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
- var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
+ var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ts.removeFileExtension(relativePath);
+ var extensionless = ts.removeFileExtension(relativePath);
+ return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
}
ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
@@ -11178,7 +11495,8 @@ var ts;
}
ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
function getThisParameter(signature) {
- if (signature.parameters.length) {
+ // callback tags do not currently support this parameters
+ if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
var thisParameter = signature.parameters[0];
if (parameterIsThisKeyword(thisParameter)) {
return thisParameter;
@@ -11263,6 +11581,9 @@ var ts;
* JavaScript file, gets the return type annotation from JSDoc.
*/
function getEffectiveReturnTypeNode(node) {
+ if (ts.isJSDocSignature(node)) {
+ return node.type && node.type.typeExpression && node.type.typeExpression.type;
+ }
return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined);
}
ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
@@ -11271,12 +11592,27 @@ var ts;
* JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
*/
function getEffectiveTypeParameterDeclarations(node) {
- return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined);
+ if (ts.isJSDocSignature(node)) {
+ return ts.emptyArray;
+ }
+ if (isJSDocTypeAlias(node)) {
+ ts.Debug.assert(node.parent.kind === 285 /* JSDocComment */);
+ var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; });
+ var templateTagNodes = templateTags;
+ templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos;
+ templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end;
+ templateTagNodes.hasTrailingComma = false;
+ return templateTagNodes;
+ }
+ return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray);
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
- var templateTag = ts.getJSDocTemplateTag(node);
- return templateTag && templateTag.typeParameters;
+ // template tags are only available when a typedef isn't already using them
+ var tag = ts.find(ts.getJSDocTags(node), function (tag) {
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ });
+ return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/**
@@ -12664,8 +13000,8 @@ var ts;
break;
case 71 /* Identifier */:
return declaration;
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */: {
+ case 297 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 145 /* QualifiedName */) {
return name.right;
@@ -12684,7 +13020,9 @@ var ts;
return undefined;
}
}
- case 292 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ return declaration.name;
+ case 296 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 248 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -12817,7 +13155,9 @@ var ts;
var tags = node.jsDocCache;
// If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
if (tags === undefined) {
- node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; });
+ var comments = ts.getJSDocCommentsAndTags(node);
+ ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
+ node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
}
return tags;
}
@@ -12935,6 +13275,11 @@ var ts;
return node.kind === 159 /* IndexSignature */;
}
ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ /* @internal */
+ function isGetOrSetAccessorDeclaration(node) {
+ return node.kind === 156 /* SetAccessor */ || node.kind === 155 /* GetAccessor */;
+ }
+ ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
// Type
function isTypePredicateNode(node) {
return node.kind === 160 /* TypePredicate */;
@@ -13063,7 +13408,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 296 /* PartiallyEmittedExpression */) {
+ while (node.kind === 300 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13419,81 +13764,89 @@ var ts;
ts.isBundle = isBundle;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 275 /* JSDocTypeExpression */;
+ return node.kind === 277 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 276 /* JSDocAllType */;
+ return node.kind === 278 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 277 /* JSDocUnknownType */;
+ return node.kind === 279 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 278 /* JSDocNullableType */;
+ return node.kind === 280 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 279 /* JSDocNonNullableType */;
+ return node.kind === 281 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 280 /* JSDocOptionalType */;
+ return node.kind === 282 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 281 /* JSDocFunctionType */;
+ return node.kind === 283 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 282 /* JSDocVariadicType */;
+ return node.kind === 284 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 283 /* JSDocComment */;
+ return node.kind === 285 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 286 /* JSDocAugmentsTag */;
+ return node.kind === 289 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 287 /* JSDocClassTag */;
+ return node.kind === 290 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocParameterTag(node) {
- return node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 292 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 289 /* JSDocReturnTag */;
+ return node.kind === 293 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 290 /* JSDocTypeTag */;
+ return node.kind === 294 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 291 /* JSDocTemplateTag */;
+ return node.kind === 295 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 292 /* JSDocTypedefTag */;
+ return node.kind === 296 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */;
+ return node.kind === 297 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */ || node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 297 /* JSDocPropertyTag */ || node.kind === 292 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 284 /* JSDocTypeLiteral */;
+ return node.kind === 286 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
+ function isJSDocCallbackTag(node) {
+ return node.kind === 291 /* JSDocCallbackTag */;
+ }
+ ts.isJSDocCallbackTag = isJSDocCallbackTag;
+ function isJSDocSignature(node) {
+ return node.kind === 287 /* JSDocSignature */;
+ }
+ ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
// Node tests
//
@@ -13502,7 +13855,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 294 /* SyntaxList */;
+ return n.kind === 298 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -13647,10 +14000,11 @@ var ts;
switch (kind) {
case 152 /* MethodSignature */:
case 157 /* CallSignature */:
+ case 287 /* JSDocSignature */:
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 163 /* ConstructorType */:
return true;
default:
@@ -13734,13 +14088,13 @@ var ts;
|| kind === 95 /* NullKeyword */
|| kind === 131 /* NeverKeyword */
|| kind === 206 /* ExpressionWithTypeArguments */
- || kind === 276 /* JSDocAllType */
- || kind === 277 /* JSDocUnknownType */
- || kind === 278 /* JSDocNullableType */
- || kind === 279 /* JSDocNonNullableType */
- || kind === 280 /* JSDocOptionalType */
- || kind === 281 /* JSDocFunctionType */
- || kind === 282 /* JSDocVariadicType */;
+ || kind === 278 /* JSDocAllType */
+ || kind === 279 /* JSDocUnknownType */
+ || kind === 280 /* JSDocNullableType */
+ || kind === 281 /* JSDocNonNullableType */
+ || kind === 282 /* JSDocOptionalType */
+ || kind === 283 /* JSDocFunctionType */
+ || kind === 284 /* JSDocVariadicType */;
}
/**
* Node test that determines whether a node is a valid type node.
@@ -13962,8 +14316,8 @@ var ts;
case 203 /* SpreadElement */:
case 207 /* AsExpression */:
case 205 /* OmittedExpression */:
- case 297 /* CommaListExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 301 /* CommaListExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -13977,12 +14331,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 296 /* PartiallyEmittedExpression */;
+ return node.kind === 300 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 295 /* NotEmittedStatement */;
+ return node.kind === 299 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14093,7 +14447,9 @@ var ts;
|| kind === 236 /* TypeAliasDeclaration */
|| kind === 147 /* TypeParameter */
|| kind === 231 /* VariableDeclaration */
- || kind === 292 /* JSDocTypedefTag */;
+ || kind === 296 /* JSDocTypedefTag */
+ || kind === 291 /* JSDocCallbackTag */
+ || kind === 297 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 233 /* FunctionDeclaration */
@@ -14128,14 +14484,14 @@ var ts;
|| kind === 213 /* VariableStatement */
|| kind === 218 /* WhileStatement */
|| kind === 225 /* WithStatement */
- || kind === 295 /* NotEmittedStatement */
- || kind === 299 /* EndOfDeclarationMarker */
- || kind === 298 /* MergeDeclarationMarker */;
+ || kind === 299 /* NotEmittedStatement */
+ || kind === 303 /* EndOfDeclarationMarker */
+ || kind === 302 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 147 /* TypeParameter */) {
- return node.parent.kind !== 291 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
+ return node.parent.kind !== 295 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14230,18 +14586,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 275 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */;
+ return node.kind >= 277 /* FirstJSDocNode */ && node.kind <= 297 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 283 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
+ return node.kind === 285 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 285 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */;
+ return node.kind >= 288 /* FirstJSDocTagNode */ && node.kind <= 297 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14292,12 +14648,12 @@ var ts;
case 231 /* VariableDeclaration */:
case 233 /* FunctionDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 275 /* JSDocTypeExpression */:
- case 278 /* JSDocNullableType */:
- case 279 /* JSDocNonNullableType */:
- case 280 /* JSDocOptionalType */:
- case 281 /* JSDocFunctionType */:
- case 282 /* JSDocVariadicType */:
+ case 277 /* JSDocTypeExpression */:
+ case 280 /* JSDocNullableType */:
+ case 281 /* JSDocNonNullableType */:
+ case 282 /* JSDocOptionalType */:
+ case 283 /* JSDocFunctionType */:
+ case 284 /* JSDocVariadicType */:
return true;
}
return false;
@@ -14787,7 +15143,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 252 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 254 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -14814,23 +15170,23 @@ var ts;
visitNode(cbNode, node.expression);
case 257 /* JsxClosingElement */:
return visitNode(cbNode, node.tagName);
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return visitNode(cbNode, node.type);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return visitNode(cbNode, node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return visitNode(cbNode, node.type);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return visitNode(cbNode, node.type);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 283 /* JSDocComment */:
+ case 285 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
+ case 297 /* JSDocPropertyTag */:
if (node.isNameFirst) {
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression);
@@ -14839,17 +15195,17 @@ var ts;
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
}
- case 289 /* JSDocReturnTag */:
+ case 293 /* JSDocReturnTag */:
return visitNode(cbNode, node.typeExpression);
- case 290 /* JSDocTypeTag */:
+ case 294 /* JSDocTypeTag */:
return visitNode(cbNode, node.typeExpression);
- case 286 /* JSDocAugmentsTag */:
+ case 289 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.class);
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
return visitNodes(cbNode, cbNodes, node.typeParameters);
- case 292 /* JSDocTypedefTag */:
+ case 296 /* JSDocTypedefTag */:
if (node.typeExpression &&
- node.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ node.typeExpression.kind === 277 /* JSDocTypeExpression */) {
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName);
}
@@ -14857,7 +15213,16 @@ var ts;
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
}
- case 284 /* JSDocTypeLiteral */:
+ case 291 /* JSDocCallbackTag */:
+ return visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression);
+ case 287 /* JSDocSignature */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters) ||
+ visitNodes(cbNode, cbNodes, node.parameters) ||
+ visitNode(cbNode, node.type);
+ case 286 /* JSDocTypeLiteral */:
if (node.jsDocPropertyTags) {
for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
var tag = _a[_i];
@@ -14865,7 +15230,7 @@ var ts;
}
}
return;
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -14873,7 +15238,13 @@ var ts;
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
- var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ var result;
+ if (languageVersion === 100 /* JSON */) {
+ result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
+ }
+ else {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ }
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
return result;
@@ -15033,6 +15404,13 @@ var ts;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
scriptKind = ts.ensureScriptKind(fileName, scriptKind);
+ if (scriptKind === 6 /* JSON */) {
+ var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
+ ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ result_1.typeReferenceDirectives = ts.emptyArray;
+ result_1.amdDependencies = ts.emptyArray;
+ return result_1;
+ }
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
clearState();
@@ -15050,25 +15428,57 @@ var ts;
return isInvalid ? entityName : undefined;
}
Parser.parseIsolatedEntityName = parseIsolatedEntityName;
- function parseJsonText(fileName, sourceText) {
- initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */);
+ function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
+ if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
+ initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
// Set source file so that errors will be reported with this file name
sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
- var result = sourceFile;
// Prime the scanner.
nextToken();
+ var pos = getNodePos();
if (token() === 1 /* EndOfFileToken */) {
+ sourceFile.statements = createNodeArray([], pos, pos);
sourceFile.endOfFileToken = parseTokenNode();
}
- else if (token() === 17 /* OpenBraceToken */ ||
- lookAhead(function () { return token() === 9 /* StringLiteral */; })) {
- result.jsonObject = parseObjectLiteralExpression();
+ else {
+ var statement = createNode(215 /* ExpressionStatement */);
+ switch (token()) {
+ case 21 /* OpenBracketToken */:
+ statement.expression = parseArrayLiteralExpression();
+ break;
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ statement.expression = parseTokenNode();
+ break;
+ case 38 /* MinusToken */:
+ if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parsePrefixUnaryExpression();
+ }
+ else {
+ statement.expression = parseObjectLiteralExpression();
+ }
+ break;
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parseLiteralNode();
+ break;
+ }
+ // falls through
+ default:
+ statement.expression = parseObjectLiteralExpression();
+ break;
+ }
+ finishNode(statement);
+ sourceFile.statements = createNodeArray([statement], pos);
sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
}
- else {
- parseExpected(17 /* OpenBraceToken */);
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
}
sourceFile.parseDiagnostics = parseDiagnostics;
+ var result = sourceFile;
clearState();
return result;
}
@@ -15092,9 +15502,11 @@ var ts;
switch (scriptKind) {
case 1 /* JS */:
case 2 /* JSX */:
- case 6 /* JSON */:
contextFlags = 65536 /* JavaScriptFile */;
break;
+ case 6 /* JSON */:
+ contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */;
+ break;
default:
contextFlags = 0 /* None */;
break;
@@ -16340,9 +16752,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(276 /* JSDocAllType */);
+ var result = createNode(278 /* JSDocAllType */);
if (postFixEquals) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, result);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -16350,7 +16762,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(279 /* JSDocNonNullableType */);
+ var result = createNode(281 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -16374,18 +16786,18 @@ var ts;
token() === 29 /* GreaterThanToken */ ||
token() === 58 /* EqualsToken */ ||
token() === 49 /* BarToken */) {
- var result = createNode(277 /* JSDocUnknownType */, pos);
+ var result = createNode(279 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(278 /* JSDocNullableType */, pos);
+ var result = createNode(280 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(281 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(283 /* JSDocFunctionType */);
nextToken();
fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -16407,12 +16819,12 @@ var ts;
var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */);
var type = parseType();
if (dotdotdot) {
- var variadic = createNode(282 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(284 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 58 /* EqualsToken */) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, type);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, type);
}
return type;
}
@@ -16496,15 +16908,19 @@ var ts;
node.initializer = parseInitializer();
return finishNode(node);
}
+ /**
+ * @returns If return type parsing succeeds
+ */
function fillSignature(returnToken, flags, signature) {
if (!(flags & 32 /* JSDoc */)) {
signature.typeParameters = parseTypeParameters();
}
signature.parameters = parseParameterList(flags);
- signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */));
- }
- function parseReturnType(returnToken, isType) {
- return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined;
+ if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
+ signature.type = parseTypeOrTypePredicate();
+ return signature.type !== undefined;
+ }
+ return true;
}
function shouldParseReturnType(returnToken, isType) {
if (returnToken === 36 /* EqualsGreaterThanToken */) {
@@ -16783,6 +17199,9 @@ var ts;
var node = createNode(172 /* ParenthesizedType */);
parseExpected(19 /* OpenParenToken */);
node.type = parseType();
+ if (!node.type) {
+ return undefined;
+ }
parseExpected(20 /* CloseParenToken */);
return finishNode(node);
}
@@ -16791,7 +17210,12 @@ var ts;
if (kind === 163 /* ConstructorType */) {
parseExpected(94 /* NewKeyword */);
}
- fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node);
+ if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) {
+ return undefined;
+ }
+ if (!node.parameters) {
+ return undefined;
+ }
return finishNode(node);
}
function parseKeywordAndNoDot() {
@@ -16947,14 +17371,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 51 /* ExclamationToken */:
- type = createJSDocPostfixType(279 /* JSDocNonNullableType */, type);
+ type = createJSDocPostfixType(281 /* JSDocNonNullableType */, type);
break;
case 55 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createJSDocPostfixType(278 /* JSDocNullableType */, type);
+ type = createJSDocPostfixType(280 /* JSDocNullableType */, type);
break;
case 21 /* OpenBracketToken */:
parseExpected(21 /* OpenBracketToken */);
@@ -17518,7 +17942,7 @@ var ts;
// 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
if (token() === 120 /* AsyncKeyword */) {
nextToken();
- // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function
+ // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
// but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) {
return 0 /* False */;
@@ -17542,7 +17966,9 @@ var ts;
// a => (b => c)
// And think that "(b =>" was actually a parenthesized arrow function with a missing
// close paren.
- fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node);
+ if (!fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node)) {
+ return undefined;
+ }
// If we couldn't get parameters, we definitely could not parse out an arrow function.
if (!node.parameters) {
return undefined;
@@ -19905,7 +20331,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var result = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos());
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -19925,6 +20351,7 @@ var ts;
}
JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
function parseJSDocComment(parent, start, length) {
+ var _a;
var saveToken = currentToken;
var saveParseDiagnosticsLength = parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
@@ -19942,7 +20369,6 @@ var ts;
parseDiagnostics.length = saveParseDiagnosticsLength;
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
return comment;
- var _a;
}
JSDocParser.parseJSDocComment = parseJSDocComment;
var JSDocState;
@@ -19953,8 +20379,9 @@ var ts;
})(JSDocState || (JSDocState = {}));
var PropertyLikeParse;
(function (PropertyLikeParse) {
- PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property";
- PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter";
+ PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
+ PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
+ PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
})(PropertyLikeParse || (PropertyLikeParse = {}));
function parseJSDocCommentWorker(start, length) {
var content = sourceText;
@@ -20002,7 +20429,7 @@ var ts;
case 57 /* AtToken */:
if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
removeTrailingNewlines(comments);
- parseTag(indent);
+ addTag(parseTag(indent));
// NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
// Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
// for malformed examples like `/** @param {string} x @returns {number} the length */`
@@ -20076,12 +20503,29 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(283 /* JSDocComment */, start);
+ var result = createNode(285 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
}
+ function isNextNonwhitespaceTokenEndOfFile() {
+ // We must use infinite lookahead, as there could be any number of newlines :(
+ while (true) {
+ nextJSDocToken();
+ if (token() === 1 /* EndOfFileToken */) {
+ return true;
+ }
+ if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
+ return false;
+ }
+ }
+ }
function skipWhitespace() {
+ if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
+ if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
+ return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
+ }
+ }
while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
nextJSDocToken();
}
@@ -20110,8 +20554,7 @@ var ts;
case "arg":
case "argument":
case "param":
- addTag(parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */, indent));
- return;
+ return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent);
case "return":
case "returns":
tag = parseReturnTag(atToken, tagName);
@@ -20123,7 +20566,10 @@ var ts;
tag = parseTypeTag(atToken, tagName);
break;
case "typedef":
- tag = parseTypedefTag(atToken, tagName);
+ tag = parseTypedefTag(atToken, tagName, indent);
+ break;
+ case "callback":
+ tag = parseCallbackTag(atToken, tagName, indent);
break;
default:
tag = parseUnknownTag(atToken, tagName);
@@ -20137,8 +20583,11 @@ var ts;
// a badly malformed tag should not be added to the list of tags
return;
}
- tag.comment = parseTagComments(indent + tag.end - tag.pos);
- addTag(tag);
+ if (!tag.comment) {
+ // some tags, like typedef and callback, have already parsed their comments earlier
+ tag.comment = parseTagComments(indent + tag.end - tag.pos);
+ }
+ return tag;
}
function parseTagComments(indent) {
var comments = [];
@@ -20201,12 +20650,15 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(285 /* JSDocTag */, atToken.pos);
+ var result = createNode(288 /* JSDocTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
}
function addTag(tag) {
+ if (!tag) {
+ return;
+ }
if (!tags) {
tags = [tag];
tagsPos = tag.pos;
@@ -20257,9 +20709,9 @@ var ts;
if (isNameFirst) {
typeExpression = tryParseTypeExpression();
}
- var result = target === 1 /* Parameter */ ?
- createNode(288 /* JSDocParameterTag */, atToken.pos) :
- createNode(293 /* JSDocPropertyTag */, atToken.pos);
+ var result = target === 1 /* Property */ ?
+ createNode(297 /* JSDocPropertyTag */, atToken.pos) :
+ createNode(292 /* JSDocParameterTag */, atToken.pos);
var comment;
if (indent !== undefined)
comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
@@ -20279,18 +20731,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) {
- if (child.kind === 288 /* JSDocParameterTag */ || child.kind === 293 /* JSDocPropertyTag */) {
+ if (child.kind === 292 /* JSDocParameterTag */ || child.kind === 297 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 166 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -20301,27 +20753,27 @@ var ts;
}
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 293 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(289 /* JSDocReturnTag */, atToken.pos);
+ var result = createNode(293 /* JSDocReturnTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 290 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 294 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(290 /* JSDocTypeTag */, atToken.pos);
+ var result = createNode(294 /* JSDocTypeTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(atToken, tagName) {
- var result = createNode(286 /* JSDocAugmentsTag */, atToken.pos);
+ var result = createNode(289 /* JSDocAugmentsTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
@@ -20349,32 +20801,23 @@ var ts;
return node;
}
function parseClassTag(atToken, tagName) {
- var tag = createNode(287 /* JSDocClassTag */, atToken.pos);
+ var tag = createNode(290 /* JSDocClassTag */, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
}
- function parseTypedefTag(atToken, tagName) {
+ function parseTypedefTag(atToken, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(292 /* JSDocTypedefTag */, atToken.pos);
+ var typedefTag = createNode(296 /* JSDocTypedefTag */, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
- typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0);
- if (typedefTag.fullName) {
- var rightNode = typedefTag.fullName;
- while (true) {
- if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) {
- // if node is identifier - use it as name
- // otherwise use name of the rightmost part that we were able to parse
- typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name;
- break;
- }
- rightNode = rightNode.body;
- }
- }
+ typedefTag.fullName = parseJSDocTypeNameWithNamespace();
+ typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
skipWhitespace();
+ typedefTag.comment = parseTagComments(indent);
typedefTag.typeExpression = typeExpression;
+ var end;
if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
var child = void 0;
var jsdocTypeLiteral = void 0;
@@ -20382,9 +20825,9 @@ var ts;
var start_3 = scanner.getStartPos();
while (child = tryParse(function () { return parseChildPropertyTag(); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_3);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_3);
}
- if (child.kind === 290 /* JSDocTypeTag */) {
+ if (child.kind === 294 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -20403,23 +20846,68 @@ var ts;
typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
childTypeTag.typeExpression :
finishNode(jsdocTypeLiteral);
+ end = typedefTag.typeExpression.end;
}
}
- return finishNode(typedefTag);
- function parseJSDocTypeNameWithNamespace(flags) {
- var pos = scanner.getTokenPos();
- var typeNameOrNamespaceName = parseJSDocIdentifierName();
- if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) {
- var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos);
- jsDocNamespaceNode.flags |= flags;
- jsDocNamespaceNode.name = typeNameOrNamespaceName;
- jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */);
- return finishNode(jsDocNamespaceNode);
+ // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
+ return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
+ }
+ function parseJSDocTypeNameWithNamespace(nested) {
+ var pos = scanner.getTokenPos();
+ var typeNameOrNamespaceName = parseJSDocIdentifierName();
+ if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) {
+ var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos);
+ if (nested) {
+ jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
}
- if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) {
- typeNameOrNamespaceName.isInJSDocNamespace = true;
+ jsDocNamespaceNode.name = typeNameOrNamespaceName;
+ jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
+ return finishNode(jsDocNamespaceNode);
+ }
+ if (typeNameOrNamespaceName && nested) {
+ typeNameOrNamespaceName.isInJSDocNamespace = true;
+ }
+ return typeNameOrNamespaceName;
+ }
+ function parseCallbackTag(atToken, tagName, indent) {
+ var callbackTag = createNode(291 /* JSDocCallbackTag */, atToken.pos);
+ callbackTag.atToken = atToken;
+ callbackTag.tagName = tagName;
+ callbackTag.fullName = parseJSDocTypeNameWithNamespace();
+ callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
+ skipWhitespace();
+ callbackTag.comment = parseTagComments(indent);
+ var child;
+ var start = scanner.getStartPos();
+ var jsdocSignature = createNode(287 /* JSDocSignature */, start);
+ jsdocSignature.parameters = [];
+ while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) {
+ jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
+ }
+ var returnTag = tryParse(function () {
+ if (token() === 57 /* AtToken */) {
+ nextJSDocToken();
+ var tag = parseTag(indent);
+ if (tag && tag.kind === 293 /* JSDocReturnTag */) {
+ return tag;
+ }
+ }
+ });
+ if (returnTag) {
+ jsdocSignature.type = returnTag;
+ }
+ callbackTag.typeExpression = finishNode(jsdocSignature);
+ return finishNode(callbackTag);
+ }
+ function getJSDocTypeAliasName(fullName) {
+ if (fullName) {
+ var rightNode = fullName;
+ while (true) {
+ if (ts.isIdentifier(rightNode) || !rightNode.body) {
+ return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
+ }
+ rightNode = rightNode.body;
}
- return typeNameOrNamespaceName;
}
}
function escapedTextsEqual(a, b) {
@@ -20435,7 +20923,7 @@ var ts;
return a.escapedText === b.escapedText;
}
function parseChildPropertyTag() {
- return parseChildParameterOrPropertyTag(0 /* Property */);
+ return parseChildParameterOrPropertyTag(1 /* Property */);
}
function parseChildParameterOrPropertyTag(target, name) {
var canParseTag = true;
@@ -20445,7 +20933,8 @@ var ts;
case 57 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target);
- if (child && child.kind === 288 /* JSDocParameterTag */ &&
+ if (child && child.kind === 292 /* JSDocParameterTag */ &&
+ target !== 4 /* CallbackParameter */ &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
}
@@ -20484,20 +20973,20 @@ var ts;
var t;
switch (tagName.escapedText) {
case "type":
- return target === 0 /* Property */ && parseTypeTag(atToken, tagName);
+ return target === 1 /* Property */ && parseTypeTag(atToken, tagName);
case "prop":
case "property":
- t = 0 /* Property */;
+ t = 1 /* Property */;
break;
case "arg":
case "argument":
case "param":
- t = 1 /* Parameter */;
+ t = 2 /* Parameter */ | 4 /* CallbackParameter */;
break;
default:
return false;
}
- if (target !== t) {
+ if (!(target & t)) {
return false;
}
var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined);
@@ -20530,7 +21019,7 @@ var ts;
break;
}
}
- var result = createNode(291 /* JSDocTemplateTag */, atToken.pos);
+ var result = createNode(295 /* JSDocTemplateTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -20579,7 +21068,7 @@ var ts;
var pos = scanner.getTokenPos();
var end = scanner.getTextPos();
var result = createNode(71 /* Identifier */, pos);
- result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end));
+ result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText());
finishNode(result, end);
nextJSDocToken();
return result;
@@ -21383,7 +21872,7 @@ var ts;
var thisParentContainer; // Container one level up
var blockScopeContainer;
var lastContainer;
- var delayedTypedefs;
+ var delayedTypeAliases;
var seenThisKeyword;
// state used by control flow analysis
var currentFlow;
@@ -21441,7 +21930,7 @@ var ts;
thisParentContainer = undefined;
blockScopeContainer = undefined;
lastContainer = undefined;
- delayedTypedefs = undefined;
+ delayedTypeAliases = undefined;
seenThisKeyword = false;
currentFlow = undefined;
currentBreakTarget = undefined;
@@ -21515,6 +22004,7 @@ var ts;
return "__constructor" /* Constructor */;
case 162 /* FunctionType */:
case 157 /* CallSignature */:
+ case 287 /* JSDocSignature */:
return "__call" /* Call */;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */:
@@ -21523,6 +22013,10 @@ var ts;
return "__index" /* Index */;
case 249 /* ExportDeclaration */:
return "__export" /* ExportStar */;
+ case 273 /* SourceFile */:
+ // json file should behave as
+ // module.exports = ...
+ return "export=" /* ExportEquals */;
case 199 /* BinaryExpression */:
if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) {
// module.exports = ...
@@ -21530,18 +22024,15 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 148 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 281 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 283 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
- case 292 /* JSDocTypedefTag */:
- var name_2 = ts.getNameOfJSDocTypedef(node);
- return typeof name_2 !== "undefined" ? name_2.escapedText : undefined;
}
}
function getDisplayName(node) {
@@ -21679,9 +22170,9 @@ var ts;
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
- if (node.kind === 292 /* JSDocTypedefTag */)
+ if (ts.isJSDocTypeAlias(node))
ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
- if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypedefTag(node)) {
+ if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
}
@@ -21846,23 +22337,6 @@ var ts;
ts.forEachChild(node, bind, bindEach);
}
function bindChildrenWorker(node) {
- // Binding of JsDocComment should be done before the current block scope container changes.
- // because the scope of JsDocComment should not be affected by whether the current node is a
- // container or not.
- if (ts.hasJSDocNodes(node)) {
- if (ts.isInJavaScriptFile(node)) {
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var j = _a[_i];
- bind(j);
- }
- }
- else {
- for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
- var j = _c[_b];
- setParentPointers(node, j);
- }
- }
- }
if (checkUnreachable(node)) {
bindEachChild(node);
return;
@@ -21928,11 +22402,9 @@ var ts;
case 186 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 283 /* JSDocComment */:
- bindJSDocComment(node);
- break;
- case 292 /* JSDocTypedefTag */:
- bindJSDocTypedefTag(node);
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
case 273 /* SourceFile */:
@@ -21947,6 +22419,7 @@ var ts;
bindEachChild(node);
break;
}
+ bindJSDoc(node);
}
function isNarrowingExpression(expr) {
switch (expr.kind) {
@@ -22548,23 +23021,10 @@ var ts;
bindInitializedVariableFlow(node);
}
}
- function bindJSDocComment(node) {
- ts.forEachChild(node, function (n) {
- if (n.kind !== 292 /* JSDocTypedefTag */) {
- bind(n);
- }
- });
- }
- function bindJSDocTypedefTag(node) {
- ts.forEachChild(node, function (n) {
- // if the node has a fullName "A.B.C", that means symbol "C" was already bound
- // when we visit "fullName"; so when we visit the name "C" as the next child of
- // the jsDocTypedefTag, we should skip binding it.
- if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) {
- return;
- }
- bind(n);
- });
+ function bindJSDocTypeAlias(node) {
+ if (node.fullName) {
+ setParentPointers(node, node.fullName);
+ }
}
function bindCallExpressionFlow(node) {
// If the target of the call expression is a function expression or arrow function we have
@@ -22596,7 +23056,7 @@ var ts;
case 237 /* EnumDeclaration */:
case 183 /* ObjectLiteralExpression */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 262 /* JsxAttributes */:
return 1 /* IsContainer */;
case 235 /* InterfaceDeclaration */:
@@ -22618,7 +23078,8 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 157 /* CallSignature */:
- case 281 /* JSDocFunctionType */:
+ case 287 /* JSDocSignature */:
+ case 283 /* JSDocFunctionType */:
case 162 /* FunctionType */:
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
@@ -22680,7 +23141,7 @@ var ts;
case 237 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 183 /* ObjectLiteralExpression */:
case 235 /* InterfaceDeclaration */:
case 262 /* JsxAttributes */:
@@ -22694,6 +23155,7 @@ var ts;
case 163 /* ConstructorType */:
case 157 /* CallSignature */:
case 158 /* ConstructSignature */:
+ case 287 /* JSDocSignature */:
case 159 /* IndexSignature */:
case 153 /* MethodDeclaration */:
case 152 /* MethodSignature */:
@@ -22703,7 +23165,9 @@ var ts;
case 233 /* FunctionDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
case 236 /* TypeAliasDeclaration */:
case 176 /* MappedType */:
// All the children of these container types are never visible through another
@@ -22878,22 +23342,35 @@ var ts;
bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */);
}
function delayedBindJSDocTypedefTag() {
- if (!delayedTypedefs) {
+ if (!delayedTypeAliases) {
return;
}
var saveContainer = container;
var saveLastContainer = lastContainer;
var saveBlockScopeContainer = blockScopeContainer;
var saveParent = parent;
- for (var _i = 0, delayedTypedefs_1 = delayedTypedefs; _i < delayedTypedefs_1.length; _i++) {
- var delay = delayedTypedefs_1[_i];
- (container = delay.container, lastContainer = delay.lastContainer, blockScopeContainer = delay.blockScopeContainer, parent = delay.parent);
- bindBlockScopedDeclaration(delay.typedef, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
+ var saveCurrentFlow = currentFlow;
+ for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
+ var typeAlias = delayedTypeAliases_1[_i];
+ var host = ts.getJSDocHost(typeAlias);
+ container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
+ blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
+ currentFlow = { flags: 2 /* Start */ };
+ parent = typeAlias;
+ bind(typeAlias.typeExpression);
+ if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) {
+ parent = typeAlias.parent;
+ bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
+ }
+ else {
+ bind(typeAlias.fullName);
+ }
}
container = saveContainer;
lastContainer = saveLastContainer;
blockScopeContainer = saveBlockScopeContainer;
parent = saveParent;
+ currentFlow = saveCurrentFlow;
}
// The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
// check for reserved words used as identifiers in strict mode code.
@@ -23045,8 +23522,6 @@ var ts;
// Here the current node is "foo", which is a container, but the scope of "MyType" should
// not be inside "foo". Therefore we always bind @typedef before bind the parent node,
// and skip binding this tag later when binding all the other jsdoc tags.
- if (ts.isInJavaScriptFile(node))
- bindJSDocTypedefTagIfAny(node);
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
// destination symbol tables are:
@@ -23077,25 +23552,22 @@ var ts;
}
else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
+ bindJSDoc(node);
}
inStrictMode = saveInStrictMode;
}
- function bindJSDocTypedefTagIfAny(node) {
- if (!ts.hasJSDocNodes(node)) {
- return;
- }
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var jsDoc = _a[_i];
- if (!jsDoc.tags) {
- continue;
+ function bindJSDoc(node) {
+ if (ts.hasJSDocNodes(node)) {
+ if (ts.isInJavaScriptFile(node)) {
+ for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
+ var j = _a[_i];
+ bind(j);
+ }
}
- for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) {
- var tag = _c[_b];
- if (tag.kind === 292 /* JSDocTypedefTag */) {
- var savedParent = parent;
- parent = jsDoc;
- bind(tag);
- parent = savedParent;
+ else {
+ for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
+ var j = _c[_b];
+ setParentPointers(node, j);
}
}
}
@@ -23130,7 +23602,7 @@ var ts;
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if (node.isInJSDocNamespace) {
var parentNode = node.parent;
- while (parentNode && parentNode.kind !== 292 /* JSDocTypedefTag */) {
+ while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
parentNode = parentNode.parent;
}
bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
@@ -23232,11 +23704,12 @@ var ts;
case 156 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */);
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
+ case 287 /* JSDocSignature */:
case 163 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 176 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 183 /* ObjectLiteralExpression */:
@@ -23292,24 +23765,23 @@ var ts;
// falls through
case 239 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 288 /* JSDocParameterTag */:
- if (node.parent.kind !== 284 /* JSDocTypeLiteral */) {
+ case 292 /* JSDocParameterTag */:
+ if (node.parent.kind === 287 /* JSDocSignature */) {
+ return bindParameter(node);
+ }
+ if (node.parent.kind !== 286 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 293 /* JSDocPropertyTag */:
+ case 297 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 292 /* JSDocTypedefTag */: {
- var fullName = node.fullName;
- if (!fullName || fullName.kind === 71 /* Identifier */) {
- (delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent });
- }
- break;
- }
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
function bindPropertyWorker(node) {
@@ -23323,6 +23795,13 @@ var ts;
if (ts.isExternalModule(file)) {
bindSourceFileAsExternalModule();
}
+ else if (ts.isJsonSourceFile(file)) {
+ bindSourceFileAsExternalModule();
+ // Create symbol equivalent for the module.exports = {}
+ var originalSymbol = file.symbol;
+ declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
+ file.symbol = originalSymbol;
+ }
}
function bindSourceFileAsExternalModule() {
bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
@@ -23662,6 +24141,9 @@ var ts;
}
}
function bindParameter(node) {
+ if (node.kind === 292 /* JSDocParameterTag */ && container.kind !== 287 /* JSDocSignature */) {
+ return;
+ }
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
@@ -23720,24 +24202,30 @@ var ts;
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
function getInferTypeContainer(node) {
- while (node) {
- var parent_2 = node.parent;
- if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) {
- return parent_2;
- }
- node = parent_2;
- }
- return undefined;
+ var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
+ return extendsType && extendsType.parent;
}
function bindTypeParameter(node) {
- if (node.parent.kind === 171 /* InferType */) {
- var container_1 = getInferTypeContainer(node.parent);
+ if (ts.isJSDocTemplateTag(node.parent)) {
+ var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent);
if (container_1) {
if (!container_1.locals) {
container_1.locals = ts.createSymbolTable();
}
declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
}
+ else {
+ declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ }
+ }
+ else if (node.parent.kind === 171 /* InferType */) {
+ var container_2 = getInferTypeContainer(node.parent);
+ if (container_2) {
+ if (!container_2.locals) {
+ container_2.locals = ts.createSymbolTable();
+ }
+ declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ }
else {
bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node));
}
@@ -23999,7 +24487,7 @@ var ts;
else {
// A ClassDeclaration is ES6 syntax.
transformFlags = subtreeFlags | 192 /* AssertES2015 */;
- // A class with a parameter property assignment, property initializer, or decorator is
+ // A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
@@ -24136,9 +24624,9 @@ var ts;
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
- // If the PropertyDeclaration has an initializer, we need to inform its ancestor
+ // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
- if (node.initializer) {
+ if (node.initializer || ts.isComputedPropertyName(node.name)) {
transformFlags |= 8192 /* ContainsPropertyInitializer */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
@@ -24362,7 +24850,7 @@ var ts;
break;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -24634,7 +25122,7 @@ var ts;
return 940049729 /* BindingPatternExcludes */;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
case 190 /* ParenthesizedExpression */:
case 97 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -24652,7 +25140,7 @@ var ts;
*/
function setParentPointers(parent, child) {
child.parent = parent;
- ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); });
+ ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
}
})(ts || (ts = {}));
/** @internal */
@@ -24850,7 +25338,8 @@ var ts;
(function (Extensions) {
Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
- Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */
+ Extensions[Extensions["Json"] = 2] = "Json";
+ Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */
})(Extensions || (Extensions = {}));
/** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
function resolvedTypeScriptOnly(resolved) {
@@ -24894,7 +25383,13 @@ var ts;
function readJson(path, host) {
try {
var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
@@ -25425,7 +25920,11 @@ var ts;
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
- var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
+ var result = jsOnly ?
+ tryResolve(Extensions.JavaScript) :
+ (tryResolve(Extensions.TypeScript) ||
+ tryResolve(Extensions.JavaScript) ||
+ (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
if (result && result.value) {
var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations);
@@ -25480,7 +25979,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
- if (!ts.pathEndsWithDirectorySeparator(candidate)) {
+ if (!ts.hasTrailingDirectorySeparator(candidate)) {
if (!onlyRecordFailures) {
var parentOfCandidate = ts.getDirectoryPath(candidate);
if (!directoryProbablyExists(parentOfCandidate, state.host)) {
@@ -25565,6 +26064,10 @@ var ts;
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ if (extensions === Extensions.Json) {
+ var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
+ return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
+ }
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
@@ -25585,9 +26088,9 @@ var ts;
function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) {
if (!onlyRecordFailures) {
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ var directory_1 = ts.getDirectoryPath(candidate);
+ if (directory_1) {
+ onlyRecordFailures = !directoryProbablyExists(directory_1, state.host);
}
}
switch (extensions) {
@@ -25597,6 +26100,8 @@ var ts;
return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
case Extensions.JavaScript:
return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
+ case Extensions.Json:
+ return tryExtension(".json" /* Json */);
}
function tryExtension(ext) {
var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
@@ -25649,8 +26154,11 @@ var ts;
}
else {
var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state);
- if (typeof jsPath === "string") {
- subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */;
+ if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) {
+ var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1);
+ subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) {
+ return ts.tryRemoveExtension(potentialSubModule_1, extension);
+ }) || potentialSubModule_1) + ".d.ts" /* Dts */;
}
else {
subModuleName = "index.d.ts";
@@ -25683,9 +26191,18 @@ var ts;
}
}
function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) {
- var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state);
+ var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
if (!file) {
- return undefined;
+ if (extensions === Extensions.TypeScript) {
+ // When resolving typescript modules, try resolving using main field as well
+ file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state);
+ if (!file) {
+ return undefined;
+ }
+ }
+ else {
+ return undefined;
+ }
}
var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host);
var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state);
@@ -25718,6 +26235,8 @@ var ts;
switch (extensions) {
case Extensions.JavaScript:
return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
+ case Extensions.Json:
+ return extension === ".json" /* Json */;
case Extensions.TypeScript:
return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
case Extensions.DtsOnly:
@@ -25788,7 +26307,7 @@ var ts;
if (packageResult) {
return packageResult;
}
- if (extensions !== Extensions.JavaScript) {
+ if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
var nodeModulesAtTypesExists = nodeModulesFolderExists;
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
@@ -26213,7 +26732,7 @@ var ts;
checkSourceFile(file);
var diagnostics = [];
ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
- checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) {
+ checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) {
if (!unusedIsError(kind)) {
diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
}
@@ -26283,6 +26802,7 @@ var ts;
var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
+ var resolvingSignaturesArray = [resolvingSignature];
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
var globals = ts.createSymbolTable();
@@ -26327,8 +26847,6 @@ var ts;
var deferredGlobalExtractSymbol;
var deferredNodes;
var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
- var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked.
- var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice
var flowLoopStart = 0;
var flowLoopCount = 0;
var sharedFlowCount = 0;
@@ -26639,17 +27157,17 @@ var ts;
}
function getJsxNamespace(location) {
if (location) {
- var file = ts.getSourceFileOfNode(location);
- if (file) {
- if (file.localJsxNamespace) {
- return file.localJsxNamespace;
+ var file_1 = ts.getSourceFileOfNode(location);
+ if (file_1) {
+ if (file_1.localJsxNamespace) {
+ return file_1.localJsxNamespace;
}
- var jsxPragma = file.pragmas.get("jsx");
+ var jsxPragma = file_1.pragmas.get("jsx");
if (jsxPragma) {
var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
- file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
- if (file.localJsxFactory) {
- return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file_1.localJsxFactory) {
+ return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText;
}
}
}
@@ -26761,6 +27279,8 @@ var ts;
function mergeSymbol(target, source) {
if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
(source.flags | target.flags) & 67108864 /* JSContainer */) {
+ var targetValueDeclaration = target.valueDeclaration;
+ ts.Debug.assert(!!(target.flags & 33554432 /* Transient */));
// Javascript static-property-assignment declarations always merge, even though they are also values
if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
// reset flag when merging instantiated module into value module that has only const enums
@@ -26786,7 +27306,12 @@ var ts;
}
if ((source.flags | target.flags) & 67108864 /* JSContainer */) {
var sourceInitializer = ts.getJSInitializerSymbol(source);
- var targetInitializer = ts.getJSInitializerSymbol(target);
+ var init = ts.getDeclaredJavascriptInitializer(targetValueDeclaration) || ts.getAssignedJavascriptInitializer(targetValueDeclaration);
+ var targetInitializer = init && init.symbol ? init.symbol : target;
+ if (!(targetInitializer.flags & 33554432 /* Transient */)) {
+ var mergedInitializer = getMergedSymbol(targetInitializer);
+ targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer;
+ }
if (sourceInitializer !== source || targetInitializer !== target) {
mergeSymbol(targetInitializer, sourceInitializer);
}
@@ -27070,7 +27595,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) {
+ if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 285 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -27269,6 +27794,12 @@ var ts;
location = location.parent;
}
break;
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ // js type aliases do not resolve names from their host, so skip past it
+ lastLocation = location;
+ location = ts.getJSDocHost(location).parent;
+ continue;
}
if (isSelfReferenceLocation(location)) {
lastSelfReferenceLocation = location;
@@ -27384,9 +27915,11 @@ var ts;
function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
- var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
- if (decl.kind === 147 /* TypeParameter */ && parent === container) {
- return true;
+ if (decl.kind === 147 /* TypeParameter */) {
+ var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
+ if (parent === container) {
+ return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias));
+ }
}
}
return false;
@@ -27597,8 +28130,8 @@ var ts;
else {
exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias);
}
- var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
+ var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias);
if (!exportDefaultSymbol && !hasSyntheticDefault) {
error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
}
@@ -27850,7 +28383,7 @@ var ts;
var symbol;
if (name.kind === 71 /* Identifier */) {
var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0;
- var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSPrototype(name, meaning) : undefined;
+ var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined;
symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true);
if (!symbol) {
return symbolFromJSPrototype;
@@ -27859,40 +28392,40 @@ var ts;
else if (name.kind === 145 /* QualifiedName */ || name.kind === 184 /* PropertyAccessExpression */) {
var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression;
var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name;
- var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
- if (!namespace || ts.nodeIsMissing(right)) {
+ var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
+ if (!namespace_1 || ts.nodeIsMissing(right)) {
return undefined;
}
- else if (namespace === unknownSymbol) {
- return namespace;
+ else if (namespace_1 === unknownSymbol) {
+ return namespace_1;
}
if (ts.isInJavaScriptFile(name)) {
- var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration);
+ var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration);
if (initializer) {
- namespace = getSymbolOfNode(initializer);
+ namespace_1 = getSymbolOfNode(initializer);
}
// Currently, IIFEs may not have a symbol and we don't know about their contents. Give up in this case.
- if (!namespace) {
+ if (!namespace_1) {
return undefined;
}
- if (namespace.valueDeclaration &&
- ts.isVariableDeclaration(namespace.valueDeclaration) &&
- namespace.valueDeclaration.initializer &&
- isCommonJsRequire(namespace.valueDeclaration.initializer)) {
- var moduleName = namespace.valueDeclaration.initializer.arguments[0];
+ if (namespace_1.valueDeclaration &&
+ ts.isVariableDeclaration(namespace_1.valueDeclaration) &&
+ namespace_1.valueDeclaration.initializer &&
+ isCommonJsRequire(namespace_1.valueDeclaration.initializer)) {
+ var moduleName = namespace_1.valueDeclaration.initializer.arguments[0];
var moduleSym = resolveExternalModuleName(moduleName, moduleName);
if (moduleSym) {
var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
if (resolvedModuleSymbol) {
- namespace = resolvedModuleSymbol;
+ namespace_1 = resolvedModuleSymbol;
}
}
}
}
- symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning);
+ symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning);
if (!symbol) {
if (!ignoreErrors) {
- error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
+ error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right));
}
return undefined;
}
@@ -27904,24 +28437,37 @@ var ts;
return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
}
/**
- * For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
+ * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
* Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
* name resolution won't work either.
+ * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
*/
- function resolveEntityNameFromJSPrototype(name, meaning) {
- if (isJSDocTypeReference(name.parent) && ts.isJSDocTag(name.parent.parent.parent)) {
- var host_1 = ts.getJSDocHost(name.parent.parent.parent);
- if (ts.isExpressionStatement(host_1) &&
- ts.isBinaryExpression(host_1.expression) &&
- ts.getSpecialPropertyAssignmentKind(host_1.expression) === 3 /* PrototypeProperty */) {
- var symbol = getSymbolOfNode(host_1.expression.left);
- if (symbol) {
- var secondaryLocation = symbol.parent.valueDeclaration;
- return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
- }
+ function resolveEntityNameFromJSSpecialAssignment(name, meaning) {
+ if (isJSDocTypeReference(name.parent)) {
+ var secondaryLocation = getJSSpecialAssignmentLocation(name.parent);
+ if (secondaryLocation) {
+ return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
}
}
}
+ function getJSSpecialAssignmentLocation(node) {
+ var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
+ if (typeAlias) {
+ return;
+ }
+ var host = ts.getJSDocHost(node);
+ if (ts.isExpressionStatement(host) &&
+ ts.isBinaryExpression(host.expression) &&
+ ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) {
+ var symbol = getSymbolOfNode(host.expression.left);
+ return symbol && symbol.parent.valueDeclaration;
+ }
+ var sig = ts.getHostSignatureFromJSDocHost(host);
+ if (sig) {
+ var symbol = getSymbolOfNode(sig);
+ return symbol && symbol.valueDeclaration;
+ }
+ }
function resolveExternalModuleName(location, moduleReferenceExpression) {
return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
}
@@ -27970,7 +28516,7 @@ var ts;
}
}
// May be an untyped module. If so, ignore resolutionDiagnostic.
- if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
+ if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
if (isForAugmentation) {
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
@@ -27982,7 +28528,22 @@ var ts;
return undefined;
}
if (moduleNotFoundError) {
- // report errors only if it was requested
+ // For relative paths, see if this was possibly a projectReference redirect
+ if (ts.pathIsRelative(moduleReference)) {
+ var sourceFile_1 = ts.getSourceFileOfNode(location);
+ var redirects = sourceFile_1.redirectedReferences;
+ if (redirects) {
+ var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
+ for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
+ var ext = _a[_i];
+ var probePath = normalizedTargetPath + ext;
+ if (redirects.indexOf(probePath) >= 0) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ return undefined;
+ }
+ }
+ }
+ }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -28429,7 +28990,7 @@ var ts;
* @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
*/
function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
- if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) {
+ if (symbol && enclosingDeclaration) {
var initialSymbol = symbol;
var meaningToLook = meaning;
while (symbol) {
@@ -28446,6 +29007,14 @@ var ts;
}
return hasAccessibleDeclarations;
}
+ else {
+ if (ts.some(symbol.declarations, hasExternalModuleSymbol)) {
+ // Any meaning of a module symbol is always accessible via an `import` type
+ return {
+ accessibility: 0 /* Accessible */
+ };
+ }
+ }
// If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
// It could be a qualified symbol and hence verify the path
// e.g.:
@@ -28511,6 +29080,11 @@ var ts;
isDeclarationVisible(declaration.parent.parent.parent)) {
return addVisibleAlias(declaration, declaration.parent.parent);
}
+ else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
+ && !ts.hasModifier(declaration, 1 /* Export */)
+ && isDeclarationVisible(declaration.parent)) {
+ return addVisibleAlias(declaration, declaration);
+ }
// Declaration is not visible
return false;
}
@@ -28678,7 +29252,7 @@ var ts;
flags: flags,
tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop },
encounteredError: false,
- symbolStack: undefined,
+ visitedSymbols: undefined,
inferTypeParameters: undefined
};
}
@@ -28770,16 +29344,25 @@ var ts;
}
if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
- return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol)));
+ return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
+ }
+ if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.flags & 32768 /* TypeParameter */ &&
+ ts.length(type.symbol.declarations) &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context) &&
+ !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined);
}
var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?");
// Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
}
if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
- var name = symbolToTypeReferenceName(type.aliasSymbol);
var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
- return ts.createTypeReferenceNode(name, typeArgumentNodes);
+ if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
+ return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
+ return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes);
}
if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) {
var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types;
@@ -28828,14 +29411,26 @@ var ts;
ts.Debug.assert(!!(type.flags & 65536 /* Object */));
var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
- var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type));
+ var appropriateConstraintTypeNode;
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
+ // We have a { [P in keyof T]: X }
+ // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
+ appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
+ }
+ else {
+ appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
+ }
+ var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
}
function createAnonymousTypeNode(type) {
var symbol = type.symbol;
+ var id;
if (symbol) {
+ var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
+ id = (isConstructorObject ? "+" : "") + getSymbolId(symbol);
if (isJavaScriptConstructor(symbol.valueDeclaration)) {
// Instance and static types share the same symbol; only add 'typeof' for the static side.
var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */;
@@ -28847,7 +29442,7 @@ var ts;
shouldWriteTypeOfFunctionSymbol()) {
return symbolToTypeNode(symbol, context, 67216319 /* Value */);
}
- else if (ts.contains(context.symbolStack, symbol)) {
+ else if (context.visitedSymbols && context.visitedSymbols.has(id)) {
// If type is an anonymous type literal in a type alias declaration, use type alias name
var typeAlias = getTypeAliasForTypeLiteral(type);
if (typeAlias) {
@@ -28861,19 +29456,13 @@ var ts;
else {
// Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
// of types allows us to catch circular references to instantiations of the same anonymous type
- if (!context.symbolStack) {
- context.symbolStack = [];
- }
- var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
- if (isConstructorObject) {
- return createTypeNodeFromObjectType(type);
- }
- else {
- context.symbolStack.push(symbol);
- var result = createTypeNodeFromObjectType(type);
- context.symbolStack.pop();
- return result;
+ if (!context.visitedSymbols) {
+ context.visitedSymbols = ts.createMap();
}
+ context.visitedSymbols.set(id, true);
+ var result = createTypeNodeFromObjectType(type);
+ context.visitedSymbols.delete(id);
+ return result;
}
}
else {
@@ -28890,7 +29479,7 @@ var ts;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
- return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively
+ return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively
(!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed
}
}
@@ -28922,11 +29511,6 @@ var ts;
var typeLiteralNode = ts.createTypeLiteralNode(members);
return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
}
- function symbolToTypeReferenceName(symbol) {
- // Unnamed function expressions and arrow functions have reserved names that we don't want to display
- var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("");
- return entityName;
- }
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
if (type.target === globalArrayType) {
@@ -28959,7 +29543,7 @@ var ts;
else {
var outerTypeParameters = type.target.outerTypeParameters;
var i = 0;
- var qualifiedName = void 0;
+ var resultType = void 0;
if (outerTypeParameters) {
var length_1 = outerTypeParameters.length;
while (i < length_1) {
@@ -28973,55 +29557,65 @@ var ts;
// the default outer type arguments), we don't show the group.
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
- var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice);
- var namePart = symbolToTypeReferenceName(parent);
- (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1;
- if (qualifiedName) {
- ts.Debug.assert(!qualifiedName.right);
- qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart);
- qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined);
- }
- else {
- qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined);
- }
+ var flags_2 = context.flags;
+ context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
+ var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice);
+ context.flags = flags_2;
+ resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
}
}
}
- var entityName = void 0;
- var nameIdentifier = symbolToTypeReferenceName(type.symbol);
- if (qualifiedName) {
- ts.Debug.assert(!qualifiedName.right);
- qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier);
- entityName = qualifiedName;
- }
- else {
- entityName = nameIdentifier;
- }
var typeArgumentNodes = void 0;
if (typeArguments.length > 0) {
var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
}
- if (typeArgumentNodes) {
- var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right;
- lastIdentifier.typeArguments = undefined;
- }
- return ts.createTypeReferenceNode(entityName, typeArgumentNodes);
+ var flags = context.flags;
+ context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
+ var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes);
+ context.flags = flags;
+ return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
}
}
- function addToQualifiedNameMissingRightIdentifier(left, right) {
- ts.Debug.assert(left.right === undefined);
- if (right.kind === 71 /* Identifier */) {
- left.right = right;
- return left;
+ function appendReferenceToType(root, ref) {
+ if (ts.isImportTypeNode(root)) {
+ // first shift type arguments
+ var innerParams = root.typeArguments;
+ if (root.qualifier) {
+ (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
+ }
+ root.typeArguments = ref.typeArguments;
+ // then move qualifiers
+ var ids = getAccessStack(ref);
+ for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
+ var id = ids_1[_i];
+ root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
+ }
+ return root;
}
- var rightPart = right;
- while (rightPart.left.kind !== 71 /* Identifier */) {
- rightPart = rightPart.left;
+ else {
+ // first shift type arguments
+ var innerParams = root.typeArguments;
+ (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
+ root.typeArguments = ref.typeArguments;
+ // then move qualifiers
+ var ids = getAccessStack(ref);
+ for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
+ var id = ids_2[_a];
+ root.typeName = ts.createQualifiedName(root.typeName, id);
+ }
+ return root;
}
- left.right = rightPart.left;
- rightPart.left = left;
- return right;
+ }
+ function getAccessStack(ref) {
+ var state = ref.typeName;
+ var ids = [];
+ while (!ts.isIdentifier(state)) {
+ ids.unshift(state.right);
+ state = state.left;
+ }
+ ids.unshift(state);
+ return ids;
}
function createTypeNodesFromResolvedType(resolvedType) {
var typeElements = [];
@@ -29168,32 +29762,47 @@ var ts;
}
return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
}
- function typeParameterToDeclaration(type, context, constraint) {
- if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ function typeParameterShadowsNameInScope(type, context) {
+ return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
+ }
+ function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
- var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
- var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.symbol.declarations[0] &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context);
+ var name = shouldUseGeneratedName
+ ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */)
+ : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
var defaultParameter = getDefaultFromTypeParameter(type);
var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
context.flags = savedContextFlags;
return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
}
+ function typeParameterToDeclaration(type, context, constraint) {
+ if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
+ }
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */);
- ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter);
+ if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 292 /* JSDocParameterTag */);
+ }
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
parameterType = getOptionalType(parameterType);
}
var parameterTypeNode = typeToTypeNodeHelper(parameterType, context);
var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone);
- var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined;
+ var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter;
+ var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined;
var name = parameterDeclaration
? parameterDeclaration.name ?
- parameterDeclaration.name.kind === 71 /* Identifier */ ?
- ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
- cloneBindingName(parameterDeclaration.name) :
+ parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
+ parameterDeclaration.name.kind === 145 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
+ cloneBindingName(parameterDeclaration.name) :
ts.symbolName(parameterSymbol)
: ts.symbolName(parameterSymbol);
var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined;
@@ -29213,7 +29822,7 @@ var ts;
}
}
}
- function lookupSymbolChain(symbol, context, meaning) {
+ function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning);
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
var chain;
@@ -29249,7 +29858,7 @@ var ts;
// If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
endOfChain ||
// If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
- !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) &&
+ (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) &&
// If a parent symbol is an anonymous type, don't write it.
!(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
return [symbol];
@@ -29281,22 +29890,54 @@ var ts;
}
return typeParameterNodes;
}
- function symbolToTypeNode(symbol, context, meaning) {
- var chain = lookupSymbolChain(symbol, context, meaning);
+ /**
+ * Given A[B][C][D], finds A[B]
+ */
+ function getTopmostIndexedAccessType(top) {
+ if (ts.isIndexedAccessTypeNode(top.objectType)) {
+ return getTopmostIndexedAccessType(top.objectType);
+ }
+ return top;
+ }
+ function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
+ var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
context.flags |= 16777216 /* InInitialEntityName */;
var rootName = getNameOfSymbolAsWritten(chain[0], context);
context.flags ^= 16777216 /* InInitialEntityName */;
var isTypeOf = meaning === 67216319 /* Value */;
if (ambientModuleSymbolRegex.test(rootName)) {
// module is root, must use `ImportTypeNode`
- var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined;
- var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context);
- return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf);
+ var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
+ var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
+ var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1)));
+ if (!nonRootParts || ts.isEntityName(nonRootParts)) {
+ if (nonRootParts) {
+ var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
+ lastId.typeArguments = undefined;
+ }
+ return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
+ }
+ else {
+ var splitNode = getTopmostIndexedAccessType(nonRootParts);
+ var qualifier = splitNode.objectType.typeName;
+ return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
+ }
}
- var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0);
- return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined);
- function createEntityNameFromSymbolChain(chain, index, stopper) {
- var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
+ var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
+ if (ts.isIndexedAccessTypeNode(entityName)) {
+ return entityName; // Indexed accesses can never be `typeof`
+ }
+ if (isTypeOf) {
+ return ts.createTypeQueryNode(entityName);
+ }
+ else {
+ var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
+ var lastTypeArgs = lastId.typeArguments;
+ lastId.typeArguments = undefined;
+ return ts.createTypeReferenceNode(entityName, lastTypeArgs);
+ }
+ function createAccessFromSymbolChain(chain, index, stopper) {
+ var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
var symbol = chain[index];
if (index === 0) {
context.flags |= 16777216 /* InInitialEntityName */;
@@ -29305,9 +29946,27 @@ var ts;
if (index === 0) {
context.flags ^= 16777216 /* InInitialEntityName */;
}
+ var parent = chain[index - 1];
+ if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) {
+ // Should use an indexed access
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (ts.isIndexedAccessTypeNode(LHS)) {
+ return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ else {
+ return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ }
var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
identifier.symbol = symbol;
- return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier;
+ if (index > stopper) {
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (!ts.isEntityName(LHS)) {
+ return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
+ }
+ return ts.createQualifiedName(LHS, identifier);
+ }
+ return identifier;
}
}
function symbolToName(symbol, context, meaning, expectsIdentifier) {
@@ -29456,6 +30115,24 @@ var ts;
return "default";
}
if (symbol.declarations && symbol.declarations.length) {
+ if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) {
+ var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */);
+ if (!file_3 || !context.tracker.moduleResolverHost) {
+ if (context.tracker.trackReferencedAmbientModule) {
+ var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
+ if (ts.length(ambientDecls)) {
+ for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
+ var decl = ambientDecls_1[_i];
+ context.tracker.trackReferencedAmbientModule(decl);
+ }
+ }
+ }
+ // ambient module, just use declaration/symbol name (fallthrough)
+ }
+ else {
+ return "\"" + ts.getResolvedExternalModuleName(context.tracker.moduleResolverHost, file_3, ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration))) + "\"";
+ }
+ }
var declaration = symbol.declarations[0];
var name = ts.getNameOfDeclaration(declaration);
if (name) {
@@ -29497,6 +30174,11 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ // Top-level jsdoc type aliases are considered exported
+ // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
+ return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
case 181 /* BindingElement */:
return isDeclarationVisible(node.parent.parent);
case 231 /* VariableDeclaration */:
@@ -30209,7 +30891,7 @@ var ts;
if (symbol.flags & 4194304 /* Prototype */) {
return links.type = getTypeOfPrototypeProperty(symbol);
}
- // CommonsJS require/module/exports all have type any.
+ // CommonsJS require and module both have type any.
if (symbol === requireSymbol || symbol === moduleSymbol) {
return links.type = anyType;
}
@@ -30219,6 +30901,10 @@ var ts;
return links.type = anyType;
}
// Handle export default expressions
+ if (ts.isSourceFile(declaration)) {
+ var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile);
+ return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType;
+ }
if (declaration.kind === 248 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
@@ -30239,7 +30925,7 @@ var ts;
declaration.kind === 184 /* PropertyAccessExpression */ && declaration.parent.kind === 199 /* BinaryExpression */) {
type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol);
}
- else if (ts.isJSDocPropertyTag(declaration)
+ else if (ts.isJSDocPropertyLikeTag(declaration)
|| ts.isPropertyAccessExpression(declaration)
|| ts.isIdentifier(declaration)
|| (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
@@ -30510,13 +31196,15 @@ var ts;
case 152 /* MethodSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
case 176 /* MappedType */:
case 170 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -30526,7 +31214,7 @@ var ts;
else if (node.kind === 170 /* ConditionalType */) {
return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
}
- var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray);
+ var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
var thisType = includeThisTypes &&
(node.kind === 234 /* ClassDeclaration */ || node.kind === 204 /* ClassExpression */ || node.kind === 235 /* InterfaceDeclaration */) &&
getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
@@ -30545,13 +31233,12 @@ var ts;
var result;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var node = _a[_i];
- if (node.kind === 235 /* InterfaceDeclaration */ || node.kind === 234 /* ClassDeclaration */ ||
- node.kind === 204 /* ClassExpression */ || node.kind === 236 /* TypeAliasDeclaration */) {
+ if (node.kind === 235 /* InterfaceDeclaration */ ||
+ node.kind === 234 /* ClassDeclaration */ ||
+ node.kind === 204 /* ClassExpression */ ||
+ ts.isTypeAlias(node)) {
var declaration = node;
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
- if (typeParameters) {
- result = appendTypeParameters(result, typeParameters);
- }
+ result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
}
}
return result;
@@ -30828,9 +31515,9 @@ var ts;
return unknownType;
}
var declaration = ts.find(symbol.declarations, function (d) {
- return d.kind === 292 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */;
+ return ts.isJSDocTypeAlias(d) || d.kind === 236 /* TypeAliasDeclaration */;
});
- var typeNode = declaration.kind === 292 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type;
+ var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
// If typeNode is missing, we will error in checkJSDocTypedefTag.
var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType;
if (popTypeResolution()) {
@@ -31035,7 +31722,7 @@ var ts;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) &&
node.parameters.every(isThislessVariableLikeDeclaration) &&
- (!typeParameters || typeParameters.every(isThislessTypeParameter));
+ typeParameters.every(isThislessTypeParameter);
}
/**
* Returns true if the class or interface member given by the symbol is free of "this" references. The
@@ -31084,6 +31771,9 @@ var ts;
var symbol = type.symbol;
var members = getMembersOfSymbol(symbol);
type.declaredProperties = getNamedMembers(members);
+ // Start with signatures at empty array in case of recursive types
+ type.declaredCallSignatures = ts.emptyArray;
+ type.declaredConstructSignatures = ts.emptyArray;
type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
@@ -31213,9 +31903,9 @@ var ts;
// If we have an existing early-bound member, combine its declarations so that we can
// report an error at each declaration.
var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
- var name_3 = ts.declarationNameToString(decl.name);
- ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); });
- error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3);
+ var name_2 = ts.declarationNameToString(decl.name);
+ ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); });
+ error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2);
lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */);
}
lateSymbol.nameType = type;
@@ -31644,10 +32334,8 @@ var ts;
var templateType = getTemplateTypeFromMappedType(type.target || type);
var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
var templateModifiers = getMappedTypeModifiers(type);
- var constraintDeclaration = type.declaration.typeParameter.constraint;
var include = keyofStringsOnly ? 32 /* StringLiteral */ : 1120 /* StringOrNumberLiteralOrUnique */;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// We have a { [P in keyof T]: X }
for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
var prop = _a[_i];
@@ -31720,15 +32408,21 @@ var ts;
instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) :
unknownType);
}
+ function getConstraintDeclarationForMappedType(type) {
+ return type.declaration.typeParameter.constraint;
+ }
+ function isMappedTypeWithKeyofConstraintDeclaration(type) {
+ var constraintDeclaration = getConstraintDeclarationForMappedType(type);
+ return constraintDeclaration.kind === 174 /* TypeOperator */ &&
+ constraintDeclaration.operator === 128 /* KeyOfKeyword */;
+ }
function getModifiersTypeFromMappedType(type) {
if (!type.modifiersType) {
- var constraintDeclaration = type.declaration.typeParameter.constraint;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
// AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
// 'keyof T' to a literal union type and we can't recover T from that type.
- type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper);
+ type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper);
}
else {
// Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
@@ -31889,9 +32583,9 @@ var ts;
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
if (type.root.isDistributive) {
- var constraint = getConstraintOfType(type.checkType);
+ var constraint = getConstraintOfType(getSimplifiedType(type.checkType));
if (constraint) {
- var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
if (!(instantiated.flags & 16384 /* Never */)) {
return instantiated;
@@ -32278,9 +32972,10 @@ var ts;
// type checking functions).
function getTypeParametersFromDeclaration(declaration) {
var result;
- ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) {
+ for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
+ var node = _a[_i];
result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
- });
+ }
return result;
}
function symbolsToArray(symbols) {
@@ -32295,10 +32990,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJavaScriptFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 280 /* JSDocOptionalType */
+ node.type && node.type.kind === 282 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 280 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -32310,7 +33005,7 @@ var ts;
return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
}
function isOptionalParameter(node) {
- if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) {
+ if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
return true;
}
if (node.initializer) {
@@ -32327,6 +33022,13 @@ var ts;
}
return false;
}
+ function isOptionalJSDocParameterTag(node) {
+ if (!ts.isJSDocParameterTag(node)) {
+ return false;
+ }
+ var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */;
+ }
function createTypePredicateFromTypePredicateNode(node) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
@@ -32384,7 +33086,7 @@ var ts;
for (var i = numTypeArguments; i < numTypeParameters; i++) {
var mapper = createTypeMapper(typeParameters, typeArguments);
var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
- if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) {
+ if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) {
defaultType = anyType;
}
typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny);
@@ -32415,6 +33117,7 @@ var ts;
for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
var param = declaration.parameters[i];
var paramSymbol = param.symbol;
+ var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
// Include parameter symbol instead of property symbol in the signature
if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false);
@@ -32427,12 +33130,13 @@ var ts;
else {
parameters.push(paramSymbol);
}
- if (param.type && param.type.kind === 177 /* LiteralType */) {
+ if (type && type.kind === 177 /* LiteralType */) {
hasLiteralTypes = true;
}
// Record a new minimum argument count if this is not an optional parameter
- var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken ||
- iife && parameters.length > iife.arguments.length && !param.type ||
+ var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
+ param.initializer || param.questionToken || param.dotDotDotToken ||
+ iife && parameters.length > iife.arguments.length && !type ||
isUntypedSignatureInJSFile ||
isJSDocOptionalParameter(param);
if (!isOptionalParameter_1) {
@@ -32466,7 +33170,7 @@ var ts;
* 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
*/
function maybeAddJsSyntheticRestParameter(declaration, parameters) {
- if (!containsArgumentsReference(declaration)) {
+ if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
return false;
}
var lastParam = ts.lastOrUndefined(declaration.parameters);
@@ -32859,7 +33563,7 @@ var ts;
var isJs = ts.isInJavaScriptFile(node);
var isJsImplicitAny = !noImplicitAny && isJs;
if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
- var missingAugmentsTag = isJs && node.parent.kind !== 286 /* JSDocAugmentsTag */;
+ var missingAugmentsTag = isJs && node.parent.kind !== 289 /* JSDocAugmentsTag */;
var diag = minTypeArgumentCount === typeParameters.length
? missingAugmentsTag
? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag
@@ -33010,7 +33714,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node)) {
+ while (node && !ts.isStatement(node) && node.kind !== 285 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -33460,7 +34164,7 @@ var ts;
includes & 4096 /* Undefined */ ? includes & 16777216 /* NonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
- return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 8374815 /* NotUnit */ ? 0 : 268435456 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -33497,7 +34201,7 @@ var ts;
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -33508,7 +34212,7 @@ var ts;
var type = unionTypes.get(id);
if (!type) {
var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */);
- type = createType(131072 /* Union */ | propagatedFlags);
+ type = createType(131072 /* Union */ | propagatedFlags | unionOfUnitTypes);
unionTypes.set(id, type);
type.types = types;
/*
@@ -33525,7 +34229,8 @@ var ts;
function getTypeFromUnionTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var aliasSymbol = getAliasSymbolForTypeNode(node);
+ links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
}
return links.resolvedType;
}
@@ -33574,6 +34279,31 @@ var ts;
}
}
}
+ // When intersecting unions of unit types we can simply intersect based on type identity.
+ // Here we remove all unions of unit types from the given list and replace them with a
+ // a single union containing an intersection of the unit types.
+ function intersectUnionsOfUnitTypes(types) {
+ var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 268435456 /* UnionOfUnitTypes */) !== 0; });
+ var unionType = types[unionIndex];
+ var intersection = unionType.types;
+ var i = types.length - 1;
+ var _loop_5 = function () {
+ var t = types[i];
+ if (t.flags & 268435456 /* UnionOfUnitTypes */) {
+ intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); });
+ ts.orderedRemoveItemAt(types, i);
+ }
+ i--;
+ };
+ while (i > unionIndex) {
+ _loop_5();
+ }
+ if (intersection === unionType.types) {
+ return false;
+ }
+ types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 268435456 /* UnionOfUnitTypes */);
+ return true;
+ }
// We normalize combinations of intersection and union types based on the distributive property of the '&'
// operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
// types with union type constituents into equivalent union types with intersection type constituents and
@@ -33608,6 +34338,12 @@ var ts;
return typeSet[0];
}
if (includes & 131072 /* Union */) {
+ if (includes & 268435456 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) {
+ // When the intersection creates a reduced set (which might mean that *all* union types have
+ // disappeared), we restart the operation to get a new set of combined flags. Once we have
+ // reduced we'll never reduce again, so this occurs at most once.
+ return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
+ }
// We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
// the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072 /* Union */) !== 0; });
@@ -33629,7 +34365,8 @@ var ts;
function getTypeFromIntersectionTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var aliasSymbol = getAliasSymbolForTypeNode(node);
+ links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
}
return links.resolvedType;
}
@@ -33806,6 +34543,10 @@ var ts;
// Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
// the type itself if no transformation is possible.
function getSimplifiedIndexedAccessType(type) {
+ if (type.simplified) {
+ return type.simplified === circularConstraintType ? type : type.simplified;
+ }
+ type.simplified = circularConstraintType;
var objectType = type.objectType;
if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) {
// Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or
@@ -33824,7 +34565,7 @@ var ts;
regularTypes.push(t);
}
}
- return getUnionType([
+ return type.simplified = getUnionType([
getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)),
getIntersectionType(stringIndexTypes)
]);
@@ -33835,7 +34576,7 @@ var ts;
// eventually anyway, but it easier to reason about.
if (ts.some(objectType.types, isMappedTypeToNever)) {
var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); });
- return getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType));
+ return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType));
}
}
// If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
@@ -33843,15 +34584,15 @@ var ts;
// construct the type Box. We do not further simplify the result because mapped types can be recursive
// and we might never terminate.
if (isGenericMappedType(objectType)) {
- return substituteIndexedMappedType(objectType, type);
+ return type.simplified = substituteIndexedMappedType(objectType, type);
}
if (objectType.flags & 32768 /* TypeParameter */) {
var constraint = getConstraintFromTypeParameter(objectType);
if (constraint && isGenericMappedType(constraint)) {
- return substituteIndexedMappedType(constraint, type);
+ return type.simplified = substituteIndexedMappedType(constraint, type);
}
}
- return type;
+ return type.simplified = type;
}
function substituteIndexedMappedType(objectType, type) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
@@ -33916,7 +34657,7 @@ var ts;
var type = createObjectType(32 /* Mapped */, node.symbol);
type.declaration = node;
type.aliasSymbol = getAliasSymbolForTypeNode(node);
- type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
links.resolvedType = type;
// Eagerly resolve the constraint type which forces an error if the constraint type circularly
// references itself through one or more type aliases.
@@ -33939,14 +34680,14 @@ var ts;
var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */);
var combinedMapper;
if (root.inferTypeParameters) {
- var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
+ var context_1 = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
if (!isDeferred) {
// We don't want inferences from constraints as they may cause us to eagerly resolve the
// conditional type instead of deferring resolution. Also, we always want strict function
// types rules (i.e. proper contravariance) for inferences.
- inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
+ inferTypes(context_1.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context_1);
}
if (!isDeferred) {
// Return union of trueType and falseType for 'any' since it matches anything
@@ -34017,7 +34758,8 @@ var ts;
var links = getNodeLinks(node);
if (!links.resolvedType) {
var checkType = getTypeFromTypeNode(node.checkType);
- var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ var aliasSymbol = getAliasSymbolForTypeNode(node);
+ var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); });
var root = {
@@ -34030,7 +34772,7 @@ var ts;
inferTypeParameters: getInferTypeParameters(node),
outerTypeParameters: outerTypeParameters,
instantiations: undefined,
- aliasSymbol: getAliasSymbolForTypeNode(node),
+ aliasSymbol: aliasSymbol,
aliasTypeArguments: aliasTypeArguments
};
links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
@@ -34129,7 +34871,7 @@ var ts;
else {
var type = createObjectType(16 /* Anonymous */, node.symbol);
type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
type = createArrayType(type);
}
@@ -34139,10 +34881,9 @@ var ts;
return links.resolvedType;
}
function getAliasSymbolForTypeNode(node) {
- return node.parent.kind === 236 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined;
+ return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined;
}
- function getAliasTypeArgumentsForTypeNode(node) {
- var symbol = getAliasSymbolForTypeNode(node);
+ function getTypeArgumentsForAliasSymbol(symbol) {
return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
}
/**
@@ -34321,8 +35062,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 119 /* AnyKeyword */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return anyType;
case 137 /* StringKeyword */:
return stringType;
@@ -34363,21 +35104,22 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 169 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 172 /* ParenthesizedType */:
- case 279 /* JSDocNonNullableType */:
- case 275 /* JSDocTypeExpression */:
+ case 281 /* JSDocNonNullableType */:
+ case 277 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
- case 281 /* JSDocFunctionType */:
+ case 286 /* JSDocTypeLiteral */:
+ case 283 /* JSDocFunctionType */:
+ case 287 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 174 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -34567,6 +35309,15 @@ var ts;
// aren't the right hand side of a generic type alias declaration we optimize by reducing the
// set of type parameters to those that are possibly referenced in the literal.
var declaration_1 = symbol.declarations[0];
+ if (ts.isInJavaScriptFile(declaration_1)) {
+ var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
+ if (paramTag) {
+ var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
+ if (paramSymbol) {
+ declaration_1 = paramSymbol.valueDeclaration;
+ }
+ }
+ }
var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
if (isJavaScriptConstructor(declaration_1)) {
var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
@@ -34608,8 +35359,8 @@ var ts;
// between the node and the type parameter declaration, if the node contains actual references to the
// type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
- var container_2 = tp.symbol.declarations[0].parent;
- if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_2; })) {
+ var container_3 = tp.symbol.declarations[0].parent;
+ if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) {
return ts.forEachChild(node, containsReference);
}
}
@@ -35459,7 +36210,7 @@ var ts;
// check excess properties against discriminant type only, not the entire union
return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors);
}
- var _loop_5 = function (prop) {
+ var _loop_6 = function (prop) {
if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
if (reportErrors) {
// We know *exactly* where things went wrong when comparing the types.
@@ -35496,7 +36247,7 @@ var ts;
};
for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
var prop = _a[_i];
- var state_3 = _loop_5(prop);
+ var state_3 = _loop_6(prop);
if (typeof state_3 === "object")
return state_3.value;
}
@@ -35802,16 +36553,19 @@ var ts;
}
}
var constraint = getConstraintForRelation(source);
- if (!constraint || constraint.flags & 1 /* Any */) {
+ if (!constraint || (source.flags & 32768 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
// A type variable with no constraint is not related to the non-primitive object type.
if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728 /* NonPrimitive */))) {
errorInfo = saveErrorInfo;
return result;
}
}
- else if (result = isRelatedTo(constraint, target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ else {
+ var instantiated = getTypeWithThisArgument(constraint, source);
+ if (result = isRelatedTo(instantiated, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
}
}
else if (source.flags & 524288 /* Index */) {
@@ -35939,10 +36693,10 @@ var ts;
var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
if (modifiersRelated) {
- var result_1;
- if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
+ var result_2;
+ if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
- return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
+ return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
}
}
return 0 /* False */;
@@ -38049,7 +38803,7 @@ var ts;
if (type.flags & 131072 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 268435456 /* UnionOfUnitTypes */);
}
return f(type) ? type : neverType;
}
@@ -39285,7 +40039,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 281 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 283 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -39721,7 +40475,7 @@ var ts;
// except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}`
var type = getContextualType(binaryExpression);
return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ?
- getTypeOfExpression(left, /*cache*/ true) : type;
+ getTypeOfExpression(left) : type;
case 53 /* AmpersandAmpersandToken */:
case 26 /* CommaToken */:
return node === right ? getContextualType(binaryExpression) : undefined;
@@ -40000,8 +40754,18 @@ var ts;
return unknownType;
}
}
- if (context.typeArguments) {
- signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); });
+ var links = getNodeLinks(context);
+ if (!links.resolvedSignatures) {
+ links.resolvedSignatures = ts.createMap();
+ }
+ var cacheKey = "" + getTypeId(valueType);
+ var cachedResolved = links.resolvedSignatures.get(cacheKey);
+ if (cachedResolved && cachedResolved !== resolvingSignaturesArray) {
+ signatures = cachedResolved;
+ }
+ else if (!cachedResolved) {
+ links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray);
+ links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures));
}
return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */);
}
@@ -40312,7 +41076,7 @@ var ts;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 179 /* ObjectBindingPattern */ || contextualType.pattern.kind === 183 /* ObjectLiteralExpression */);
- var isInJSFile = ts.isInJavaScriptFile(node);
+ var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node);
var isJSObjectLiteral = !contextualType && isInJSFile;
var typeFlags = 0;
var patternWithComputedProperties = false;
@@ -40908,6 +41672,37 @@ var ts;
}
return undefined;
}
+ function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) {
+ var links = getNodeLinks(openingLikeElement);
+ if (!links.resolvedSignatures) {
+ links.resolvedSignatures = ts.createMap();
+ }
+ var cacheKey = "" + getTypeId(elementType);
+ if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) {
+ return;
+ }
+ else if (links.resolvedSignatures.get(cacheKey)) {
+ return links.resolvedSignatures.get(cacheKey);
+ }
+ links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray);
+ // Resolve the signatures, preferring constructor
+ var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
+ if (signatures.length === 0) {
+ // No construct signatures, try call signatures
+ signatures = getSignaturesOfType(elementType, 0 /* Call */);
+ if (signatures.length === 0) {
+ // We found no signatures at all, which is an error
+ if (reportErrors) {
+ error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName));
+ }
+ return;
+ }
+ }
+ // Instantiate in context of source type
+ var results = instantiateJsxSignatures(openingLikeElement, signatures);
+ links.resolvedSignatures.set(cacheKey, results);
+ return results;
+ }
/**
* Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType.
* For instance:
@@ -40963,19 +41758,10 @@ var ts;
return anyType;
}
// Get the element instance type (the result of newing or invoking this tag)
- // Resolve the signatures, preferring constructor
- var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
- if (signatures.length === 0) {
- // No construct signatures, try call signatures
- signatures = getSignaturesOfType(elementType, 0 /* Call */);
- if (signatures.length === 0) {
- // We found no signatures at all, which is an error
- error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName));
- return unknownType;
- }
+ var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true);
+ if (!ts.length(instantiatedSignatures)) {
+ return unknownType;
}
- // Instantiate in context of source type
- var instantiatedSignatures = instantiateJsxSignatures(openingLikeElement, signatures);
var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */);
// If we should include all stateless attributes type, then get all attributes type from all stateless function signature.
// Otherwise get only attributes type from the signature picked by choose-overload logic.
@@ -41199,7 +41985,7 @@ var ts;
// Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
if (ts.length(openingLikeElement.attributes.properties)) {
var reportedError = false;
- var _loop_6 = function (prop) {
+ var _loop_7 = function (prop) {
if (ts.isJsxSpreadAttribute(prop))
return "continue";
var name = ts.idText(prop.name);
@@ -41213,7 +41999,7 @@ var ts;
};
for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) {
var prop = _c[_b];
- _loop_6(prop);
+ _loop_7(prop);
}
if (reportedError) {
return;
@@ -42484,10 +43270,10 @@ var ts;
var isDecorator = node.kind === 149 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
var typeArguments;
- if (!isDecorator && !isJsxOpeningOrSelfClosingElement) {
+ if (!isDecorator) {
typeArguments = node.typeArguments;
// We already perform checking on the type arguments on the class declaration itself.
- if (isTaggedTemplate || node.expression.kind !== 97 /* SuperKeyword */) {
+ if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) {
ts.forEach(typeArguments, checkSourceElement);
}
}
@@ -43012,28 +43798,6 @@ var ts;
*/
function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) {
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
- return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray);
- }
- /**
- * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature.
- * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible
- * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element.
- * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
- * the function will fill it up with appropriate candidate signatures
- * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions.
- * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures
- */
- function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) {
- // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType)
- if (elementType.flags & 131072 /* Union */) {
- var types = elementType.types;
- var result = void 0;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var type = types_16[_i];
- result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray);
- }
- return result;
- }
var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */);
if (callSignatures && callSignatures.length > 0) {
return resolveCall(openingLikeElement, callSignatures, candidatesOutArray);
@@ -43053,7 +43817,18 @@ var ts;
case 256 /* JsxOpeningElement */:
case 255 /* JsxSelfClosingElement */:
// This code-path is called by language service
- return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature;
+ var exprTypes = checkExpression(node.tagName);
+ return forEachType(exprTypes, function (exprType) {
+ var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray);
+ if (sfcResult && sfcResult !== unknownSignature) {
+ return sfcResult;
+ }
+ var sigs = getInstantiatedJsxSignatures(node, exprType);
+ if (candidatesOutArray && ts.length(sigs)) {
+ candidatesOutArray.push.apply(candidatesOutArray, sigs);
+ }
+ return ts.length(sigs) ? sigs[0] : unknownSignature;
+ }) || unknownSignature;
}
ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -43251,8 +44026,8 @@ var ts;
if (allowSyntheticDefaultImports && type && type !== unknownType) {
var synthType = type;
if (!synthType.syntheticType) {
- var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
+ var file_4 = ts.find(originalSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_4, originalSymbol, /*dontResolveAlias*/ false);
if (hasSyntheticDefault) {
var memberTable = ts.createSymbolTable();
var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
@@ -43706,7 +44481,7 @@ var ts;
checkGrammarForGenerator(node);
}
var links = getNodeLinks(node);
- var type = getTypeOfSymbol(node.symbol);
+ var type = getTypeOfSymbol(getMergedSymbol(node.symbol));
if (isTypeAny(type)) {
return type;
}
@@ -43940,8 +44715,8 @@ var ts;
}
if (type.flags & 393216 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var t = types_17[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -45036,7 +45811,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
- if (node.kind !== 159 /* IndexSignature */ && node.kind !== 281 /* JSDocFunctionType */) {
+ if (node.kind !== 159 /* IndexSignature */ && node.kind !== 283 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -45499,7 +46274,7 @@ var ts;
n.parent.kind !== 234 /* ClassDeclaration */ &&
n.parent.kind !== 204 /* ClassExpression */ &&
n.flags & 4194304 /* Ambient */) {
- if (!(flags & 2 /* Ambient */)) {
+ if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
// It is nested in an ambient context, which means it is automatically exported
flags |= 1 /* Export */;
}
@@ -45769,8 +46544,9 @@ var ts;
switch (d.kind) {
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
- // A jsdoc typedef is, by definition, a type alias
- case 292 /* JSDocTypedefTag */:
+ // A jsdoc typedef and callback are, by definition, type aliases
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 238 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -45792,10 +46568,10 @@ var ts;
case 242 /* ImportEqualsDeclaration */:
case 245 /* NamespaceImport */:
case 244 /* ImportClause */:
- var result_2 = 0 /* None */;
+ var result_3 = 0 /* None */;
var target = resolveAlias(getSymbolOfNode(d));
- ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); });
- return result_2;
+ ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); });
+ return result_3;
case 231 /* VariableDeclaration */:
case 181 /* BindingElement */:
case 233 /* FunctionDeclaration */:
@@ -46239,7 +47015,7 @@ var ts;
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
}
}
- function checkJSDocTypedefTag(node) {
+ function checkJSDocTypeAliasTag(node) {
if (!node.typeExpression) {
// If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
@@ -46363,7 +47139,13 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
- if (potentiallyUnusedIdentifiers) {
+ if (produceDiagnostics) {
+ var sourceFile = ts.getSourceFileOfNode(node);
+ var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
+ if (!potentiallyUnusedIdentifiers) {
+ potentiallyUnusedIdentifiers = [];
+ allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
+ }
// TODO: GH#22580
// Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
potentiallyUnusedIdentifiers.push(node);
@@ -46373,10 +47155,6 @@ var ts;
for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
var node = potentiallyUnusedIdentifiers_1[_i];
switch (node.kind) {
- case 273 /* SourceFile */:
- case 238 /* ModuleDeclaration */:
- checkUnusedModuleMembers(node, addDiagnostic);
- break;
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
checkUnusedClassMembers(node, addDiagnostic);
@@ -46385,6 +47163,8 @@ var ts;
case 235 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 273 /* SourceFile */:
+ case 238 /* ModuleDeclaration */:
case 212 /* Block */:
case 240 /* CaseBlock */:
case 219 /* ForStatement */:
@@ -46417,33 +47197,6 @@ var ts;
}
}
}
- function checkUnusedLocalsAndParameters(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- node.locals.forEach(function (local) {
- // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
- // If it's a type parameter merged with a parameter, check if the parameter-side is used.
- if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) {
- if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) {
- var parameter = ts.getRootDeclaration(local.valueDeclaration);
- var name = ts.getNameOfDeclaration(local.valueDeclaration);
- if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
- addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
- }
- }
- else {
- ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); });
- }
- }
- });
- }
- }
- function isRemovedPropertyFromObjectSpread(node) {
- if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) {
- var lastElement = ts.lastOrUndefined(node.parent.elements);
- return lastElement !== node && !!lastElement.dotDotDotToken;
- }
- return false;
- }
function errorUnusedLocal(declaration, name, addDiagnostic) {
var node = ts.getNameOfDeclaration(declaration) || declaration;
if (isIdentifierThatStartsWithUnderScore(node)) {
@@ -46453,10 +47206,8 @@ var ts;
return;
}
}
- if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) {
- var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
- }
+ var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
}
function parameterNameStartsWithUnderscore(parameterName) {
return parameterName && isIdentifierThatStartsWithUnderScore(parameterName);
@@ -46504,7 +47255,7 @@ var ts;
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- if (!(node.flags & 4194304 /* Ambient */) && typeParameters && ts.last(getSymbolOfNode(node).declarations) === node) {
+ if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) {
for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
var typeParameter = typeParameters_2[_i];
if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) {
@@ -46513,50 +47264,91 @@ var ts;
}
}
}
- function checkUnusedModuleMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
- var unusedImports_1 = ts.createMap();
- node.locals.forEach(function (local) {
- if (local.isReferenced || local.exportSymbol)
- return;
- for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
- var declaration = _a[_i];
- if (ts.isAmbientModule(declaration))
- continue;
- if (isImportedDeclaration(declaration)) {
- var importClause = importClauseFromImported(declaration);
- var key = String(getNodeId(importClause));
- var group_1 = unusedImports_1.get(key);
- if (group_1) {
- group_1[1].push(declaration);
- }
- else {
- unusedImports_1.set(key, [importClause, [declaration]]);
+ function addToGroup(map, key, value, getKey) {
+ var keyString = String(getKey(key));
+ var group = map.get(keyString);
+ if (group) {
+ group[1].push(value);
+ }
+ else {
+ map.set(keyString, [key, [value]]);
+ }
+ }
+ function tryGetRootParameterDeclaration(node) {
+ return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
+ }
+ function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
+ if (nodeWithLocals.flags & 4194304 /* Ambient */)
+ return;
+ // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
+ var unusedImports = ts.createMap();
+ var unusedDestructures = ts.createMap();
+ nodeWithLocals.locals.forEach(function (local) {
+ // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
+ // If it's a type parameter merged with a parameter, check if the parameter-side is used.
+ if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
+ return;
+ }
+ for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ if (ts.isAmbientModule(declaration))
+ continue;
+ if (isImportedDeclaration(declaration)) {
+ addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
+ }
+ else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
+ // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
+ var lastElement = ts.last(declaration.parent.elements);
+ if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
+ addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
+ }
+ }
+ else {
+ var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
+ if (parameter) {
+ var name = ts.getNameOfDeclaration(local.valueDeclaration);
+ if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
+ addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
}
}
else {
errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
}
}
- });
- unusedImports_1.forEach(function (_a) {
- var importClause = _a[0], unuseds = _a[1];
- var importDecl = importClause.parent;
- if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
- for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
- var unused = unuseds_1[_i];
- errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
- }
+ }
+ });
+ unusedImports.forEach(function (_a) {
+ var importClause = _a[0], unuseds = _a[1];
+ var importDecl = importClause.parent;
+ if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
+ for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
+ var unused = unuseds_1[_i];
+ errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
}
- else if (unuseds.length === 1) {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else if (unuseds.length === 1) {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
+ }
+ });
+ unusedDestructures.forEach(function (_a) {
+ var bindingPattern = _a[0], bindingElements = _a[1];
+ var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
+ if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) {
+ for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
+ var e = bindingElements_1[_i];
+ addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier))));
}
- else {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)));
- }
- });
- }
+ }
+ else if (bindingElements.length === 1) {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))));
+ }
+ else {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
+ }
+ });
}
function isImportedDeclaration(node) {
return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */;
@@ -47731,7 +48523,7 @@ var ts;
var declaration = declarations_6[_i];
// If this declaration has too few or too many type parameters, we report an error
var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
- var numTypeParameters = ts.length(sourceParameters);
+ var numTypeParameters = sourceParameters.length;
if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
return false;
}
@@ -47879,7 +48671,7 @@ var ts;
function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
// iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
var issuedMemberError = false;
- var _loop_7 = function (member) {
+ var _loop_8 = function (member) {
if (ts.hasStaticModifier(member)) {
return "continue";
}
@@ -47898,7 +48690,7 @@ var ts;
};
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- _loop_7(member);
+ _loop_8(member);
}
if (!issuedMemberError) {
// check again with diagnostics to generate a less-specific error
@@ -48747,9 +49539,9 @@ var ts;
}
}
// Checks for export * conflicts
- var exports = getExportsOfModule(moduleSymbol);
- if (exports) {
- exports.forEach(function (_a, id) {
+ var exports_1 = getExportsOfModule(moduleSymbol);
+ if (exports_1) {
+ exports_1.forEach(function (_a, id) {
var declarations = _a.declarations, flags = _a.flags;
if (id === "__export") {
return;
@@ -48855,27 +49647,28 @@ var ts;
return checkInferType(node);
case 178 /* ImportType */:
return checkImportType(node);
- case 286 /* JSDocAugmentsTag */:
+ case 289 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 292 /* JSDocTypedefTag */:
- return checkJSDocTypedefTag(node);
- case 288 /* JSDocParameterTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ return checkJSDocTypeAliasTag(node);
+ case 292 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
checkSignatureDeclaration(node);
// falls through
- case 279 /* JSDocNonNullableType */:
- case 278 /* JSDocNullableType */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
- case 284 /* JSDocTypeLiteral */:
+ case 281 /* JSDocNonNullableType */:
+ case 280 /* JSDocNullableType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
+ case 286 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 175 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -48987,8 +49780,8 @@ var ts;
var paramTag = parent.parent;
if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) {
// Else we will add a diagnostic, see `checkJSDocVariadicType`.
- var host_2 = ts.getHostSignatureFromJSDoc(paramTag);
- if (host_2) {
+ var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
+ if (host_1) {
/*
Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
So in the following situation we will not create an array type:
@@ -48996,7 +49789,7 @@ var ts;
function f(a) {}
Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
*/
- var lastParamDeclaration = ts.lastOrUndefined(host_2.parameters);
+ var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
if (!lastParamDeclaration ||
symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
@@ -49059,6 +49852,9 @@ var ts;
return ts.Debug.assertNever(kind);
}
}
+ function getPotentiallyUnusedIdentifiers(sourceFile) {
+ return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
+ }
// Fully type check a source file and collect the relevant diagnostics.
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
@@ -49074,25 +49870,19 @@ var ts;
ts.clear(potentialThisCollisions);
ts.clear(potentialNewTargetCollisions);
deferredNodes = [];
- if (produceDiagnostics) {
- ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
- allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
- }
ts.forEach(node.statements, checkSourceElement);
checkDeferredNodes();
if (ts.isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
- checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) {
+ checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
});
}
deferredNodes = undefined;
- seenPotentiallyUnusedIdentifiers.clear();
- potentiallyUnusedIdentifiers = undefined;
if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
@@ -49388,10 +50178,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 288 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 292 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 291 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 295 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -49931,6 +50721,7 @@ var ts;
function isRequiredInitializedParameter(parameter) {
return strictNullChecks &&
!isOptionalParameter(parameter) &&
+ !ts.isJSDocParameterTag(parameter) &&
parameter.initializer &&
!ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
}
@@ -50181,7 +50972,22 @@ var ts;
var symbol = node && getSymbolOfNode(node);
return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
},
- getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; },
+ getAllAccessorDeclarations: function (accessor) {
+ accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration);
+ var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */;
+ var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
+ var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
+ var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
+ var setAccessor = accessor.kind === 156 /* SetAccessor */ ? accessor : otherAccessor;
+ var getAccessor = accessor.kind === 155 /* GetAccessor */ ? accessor : otherAccessor;
+ return {
+ firstAccessor: firstAccessor,
+ secondAccessor: secondAccessor,
+ setAccessor: setAccessor,
+ getAccessor: getAccessor
+ };
+ }
};
function isInHeritageClause(node) {
return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 267 /* HeritageClause */;
@@ -50217,8 +51023,8 @@ var ts;
var decl = _a[_i];
// check meaning of the local symbol to see if declaration needs to be analyzed further
if (decl.symbol && decl.symbol.flags & meaning) {
- var file = ts.getSourceFileOfNode(decl);
- var typeReferenceDirective = fileToDirective.get(file.path);
+ var file_5 = ts.getSourceFileOfNode(decl);
+ var typeReferenceDirective = fileToDirective.get(file_5.path);
if (typeReferenceDirective) {
(typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
}
@@ -50253,8 +51059,8 @@ var ts;
// check that at least one declaration of top level symbol originates from type declaration file
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
- var file = ts.getSourceFileOfNode(decl);
- if (fileToDirective.has(file.path)) {
+ var file_6 = ts.getSourceFileOfNode(decl);
+ if (fileToDirective.has(file_6.path)) {
return true;
}
}
@@ -50272,25 +51078,25 @@ var ts;
function initializeTypeChecker() {
// Bind all source files and propagate errors
for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
- var file = _a[_i];
- ts.bindSourceFile(file, compilerOptions);
+ var file_7 = _a[_i];
+ ts.bindSourceFile(file_7, compilerOptions);
}
// Initialize global symbol table
var augmentations;
for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
- var file = _c[_b];
- if (!ts.isExternalOrCommonJsModule(file)) {
- mergeSymbolTable(globals, file.locals);
+ var file_8 = _c[_b];
+ if (!ts.isExternalOrCommonJsModule(file_8)) {
+ mergeSymbolTable(globals, file_8.locals);
}
- if (file.patternAmbientModules && file.patternAmbientModules.length) {
- patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
+ if (file_8.patternAmbientModules && file_8.patternAmbientModules.length) {
+ patternAmbientModules = ts.concatenate(patternAmbientModules, file_8.patternAmbientModules);
}
- if (file.moduleAugmentations.length) {
- (augmentations || (augmentations = [])).push(file.moduleAugmentations);
+ if (file_8.moduleAugmentations.length) {
+ (augmentations || (augmentations = [])).push(file_8.moduleAugmentations);
}
- if (file.symbol && file.symbol.globalExports) {
+ if (file_8.symbol && file_8.symbol.globalExports) {
// Merge in UMD exports with first-in-wins semantics (see #9771)
- var source = file.symbol.globalExports;
+ var source = file_8.symbol.globalExports;
source.forEach(function (sourceSymbol, id) {
if (!globals.has(id)) {
globals.set(id, sourceSymbol);
@@ -50742,7 +51548,7 @@ var ts;
}
function checkGrammarClassLikeDeclaration(node) {
var file = ts.getSourceFileOfNode(node);
- return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(ts.getEffectiveTypeParameterDeclarations(node), file);
+ return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
}
function checkGrammarArrowFunction(node, file) {
if (!ts.isArrowFunction(node)) {
@@ -51427,8 +52233,8 @@ var ts;
}
function checkGrammarConstructorTypeParameters(node) {
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- if (typeParameters) {
- var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end;
+ if (ts.isNodeArray(typeParameters)) {
+ var pos = typeParameters.pos, end = typeParameters.end;
return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
}
}
@@ -51578,7 +52384,7 @@ var ts;
}
function checkGrammarImportCallExpression(node) {
if (moduleKind === ts.ModuleKind.ES2015) {
- return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules);
+ return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext);
}
if (node.typeArguments) {
return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
@@ -51657,10 +52463,8 @@ var ts;
if (!elements || elements === ts.emptyArray) {
elements = [];
}
- else {
- if (ts.isNodeArray(elements)) {
- return elements;
- }
+ else if (ts.isNodeArray(elements)) {
+ return elements;
}
var array = elements;
array.pos = -1;
@@ -51720,6 +52524,13 @@ var ts;
node.text = text;
return node;
}
+ ts.createStringLiteral = createStringLiteral;
+ function createRegularExpressionLiteral(text) {
+ var node = createSynthesizedNode(12 /* RegularExpressionLiteral */);
+ node.text = text;
+ return node;
+ }
+ ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
function createLiteralFromNode(sourceNode) {
var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
node.textSourceNode = sourceNode;
@@ -51753,7 +52564,7 @@ var ts;
recordTempVariable(name);
}
if (reservedInNestedScopes) {
- name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */;
+ name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
}
return name;
}
@@ -51779,7 +52590,7 @@ var ts;
/** Create a unique name based on the supplied text. */
function createOptimisticUniqueName(text) {
var name = createIdentifier(text);
- name.autoGenerateFlags = 3 /* Unique */ | 32 /* Optimistic */;
+ name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
@@ -51788,18 +52599,15 @@ var ts;
/** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
function createFileLevelUniqueName(text) {
var name = createOptimisticUniqueName(text);
- name.autoGenerateFlags |= 64 /* FileLevel */;
+ name.autoGenerateFlags |= 32 /* FileLevel */;
return name;
}
ts.createFileLevelUniqueName = createFileLevelUniqueName;
- function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) {
- var name = createIdentifier("");
- name.autoGenerateFlags = 4 /* Node */;
+ function getGeneratedNameForNode(node, flags) {
+ var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : "");
+ name.autoGenerateFlags = 4 /* Node */ | flags;
name.autoGenerateId = nextAutoGenerateId;
name.original = node;
- if (shouldSkipNameGenerationScope) {
- name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */;
- }
nextAutoGenerateId++;
return name;
}
@@ -51890,7 +52698,7 @@ var ts;
ts.updateQualifiedName = updateQualifiedName;
function parenthesizeForComputedName(expression) {
return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) ||
- expression.kind === 297 /* CommaListExpression */ ?
+ expression.kind === 301 /* CommaListExpression */ ?
createParen(expression) :
expression;
}
@@ -52940,6 +53748,13 @@ var ts;
return block;
}
ts.createBlock = createBlock;
+ /* @internal */
+ function createExpressionStatement(expression) {
+ var node = createSynthesizedNode(215 /* ExpressionStatement */);
+ node.expression = expression;
+ return node;
+ }
+ ts.createExpressionStatement = createExpressionStatement;
function updateBlock(node, statements) {
return node.statements !== statements
? updateNode(createBlock(statements, node.multiLine), node)
@@ -52966,9 +53781,7 @@ var ts;
}
ts.createEmptyStatement = createEmptyStatement;
function createStatement(expression) {
- var node = createSynthesizedNode(215 /* ExpressionStatement */);
- node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
- return node;
+ return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression));
}
ts.createStatement = createStatement;
function updateStatement(node, expression) {
@@ -53864,7 +54677,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(295 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(299 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -53876,7 +54689,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(303 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53888,7 +54701,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(298 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(302 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53903,7 +54716,7 @@ var ts;
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(296 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(300 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -53919,7 +54732,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 297 /* CommaListExpression */) {
+ if (node.kind === 301 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) {
@@ -53929,7 +54742,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(297 /* CommaListExpression */);
+ var node = createSynthesizedNode(301 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -53940,15 +54753,31 @@ var ts;
: node;
}
ts.updateCommaList = updateCommaList;
- function createBundle(sourceFiles) {
+ function createBundle(sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
var node = ts.createNode(274 /* Bundle */);
+ node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function updateBundle(node, sourceFiles) {
- if (node.sourceFiles !== sourceFiles) {
- return createBundle(sourceFiles);
+ function createUnparsedSourceFile(text) {
+ var node = ts.createNode(275 /* UnparsedSource */);
+ node.text = text;
+ return node;
+ }
+ ts.createUnparsedSourceFile = createUnparsedSourceFile;
+ function createInputFiles(javascript, declaration) {
+ var node = ts.createNode(276 /* InputFiles */);
+ node.javascriptText = javascript;
+ node.declarationText = declaration;
+ return node;
+ }
+ ts.createInputFiles = createInputFiles;
+ function updateBundle(node, sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
+ if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
+ return createBundle(sourceFiles, prepends);
}
return node;
}
@@ -54220,6 +55049,15 @@ var ts;
return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
}
ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
+ function moveSyntheticComments(node, original) {
+ setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
+ setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
+ var emit = getOrCreateEmitNode(original);
+ emit.leadingComments = undefined;
+ emit.trailingComments = undefined;
+ return node;
+ }
+ ts.moveSyntheticComments = moveSyntheticComments;
/**
* Gets the constant value to emit for an expression.
*/
@@ -55192,7 +56030,7 @@ var ts;
// if should be wrapped in parens since comma operator has the lowest precedence
var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
return emittedExpression.kind === 199 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ ||
- emittedExpression.kind === 297 /* CommaListExpression */
+ emittedExpression.kind === 301 /* CommaListExpression */
? ts.createParen(e)
: e;
}
@@ -55212,7 +56050,7 @@ var ts;
var check = ts.skipPartiallyEmittedExpressions(e);
return (check.kind === 204 /* ClassExpression */ ||
check.kind === 191 /* FunctionExpression */ ||
- check.kind === 297 /* CommaListExpression */ ||
+ check.kind === 301 /* CommaListExpression */ ||
ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */)
? ts.createParen(e)
: e;
@@ -55333,6 +56171,7 @@ var ts;
switch (member.kind) {
case 164 /* TypeQuery */:
case 174 /* TypeOperator */:
+ case 171 /* InferType */:
return ts.createParenthesizedType(member);
}
return parenthesizeElementTypeMember(member);
@@ -55376,7 +56215,7 @@ var ts;
case 184 /* PropertyAccessExpression */:
node = node.expression;
continue;
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -55406,7 +56245,7 @@ var ts;
case 207 /* AsExpression */:
case 208 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -55443,7 +56282,7 @@ var ts;
case 189 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 207 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 208 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -55931,7 +56770,7 @@ var ts;
statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements);
}
var declarations = context.endLexicalEnvironment();
- return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements);
+ return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements);
}
ts.visitLexicalEnvironment = visitLexicalEnvironment;
/**
@@ -56228,9 +57067,9 @@ var ts;
case 273 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -56286,7 +57125,7 @@ var ts;
case 214 /* EmptyStatement */:
case 205 /* OmittedExpression */:
case 230 /* DebuggerStatement */:
- case 295 /* NotEmittedStatement */:
+ case 299 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -56665,10 +57504,10 @@ var ts;
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -56682,8 +57521,8 @@ var ts;
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements)
- : ts.addRange(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements)
+ : ts.prependRange(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -56833,16 +57672,6 @@ var ts;
return node ? ts.getNodeId(node) : 0;
}
ts.getOriginalNodeId = getOriginalNodeId;
- function getNamedImportCount(node) {
- if (!(node.importClause && node.importClause.namedBindings))
- return 0;
- var names = node.importClause.namedBindings;
- if (!names)
- return 0;
- if (!ts.isNamedImports(names))
- return 0;
- return names.elements.length;
- }
function containsDefaultReference(node) {
if (!node)
return false;
@@ -56853,12 +57682,40 @@ var ts;
function isNamedDefaultReference(e) {
return e.propertyName && e.propertyName.escapedText === "default" /* Default */;
}
+ function chainBundle(transformSourceFile) {
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ return node.kind === 273 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ }
+ function transformBundle(node) {
+ return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
+ }
+ }
+ ts.chainBundle = chainBundle;
function getImportNeedsImportStarHelper(node) {
- return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings));
+ if (!!ts.getNamespaceDeclarationNode(node)) {
+ return true;
+ }
+ var bindings = node.importClause && node.importClause.namedBindings;
+ if (!bindings) {
+ return false;
+ }
+ if (!ts.isNamedImports(bindings))
+ return false;
+ var defaultRefCount = 0;
+ for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
+ var binding = _a[_i];
+ if (isNamedDefaultReference(binding)) {
+ defaultRefCount++;
+ }
+ }
+ // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
+ return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
}
ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
function getImportNeedsImportDefaultHelper(node) {
- return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings));
+ // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
+ return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings)));
}
ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
@@ -57595,7 +58452,21 @@ var ts;
* at the next execution site, in document order
*/
var pendingExpressions;
- return transformSourceFile;
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ if (node.kind === 274 /* Bundle */) {
+ return transformBundle(node);
+ }
+ return transformSourceFile(node);
+ }
+ function transformBundle(node) {
+ return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
+ if (prepend.kind === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.javascriptText);
+ }
+ return prepend;
+ }));
+ }
/**
* Transform TypeScript-specific syntax in a SourceFile.
*
@@ -58085,7 +58956,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, context.endLexicalEnvironment());
+ ts.prependRange(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -58290,7 +59161,7 @@ var ts;
// record an alias as the class name is not in scope for statics.
enableSubstitutionForClassAliases();
var alias = ts.getSynthesizedClone(temp);
- alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */;
+ alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
classAliases[ts.getOriginalNodeId(node)] = alias;
}
// To preserve the behavior of the old emitter, we explicitly indent
@@ -58567,7 +59438,7 @@ var ts;
function transformInitializedProperty(property, receiver) {
// We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
- ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */)))
+ ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
: property.name;
var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression);
var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
@@ -59597,6 +60468,11 @@ var ts;
// we can safely elide the parentheses here, as a new synthetic
// ParenthesizedExpression will be inserted if we remove parentheses too
// aggressively.
+ // HOWEVER - if there are leading comments on the expression itself, to handle ASI
+ // correctly for return and throw, we must keep the parenthesis
+ if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
+ return ts.updateParen(node, expression);
+ }
return ts.createPartiallyEmittedExpression(expression, node);
}
return ts.visitEachChild(node, visitor, context);
@@ -59702,8 +60578,9 @@ var ts;
currentNamespaceContainerName = localName;
var statements = [];
startLexicalEnvironment();
- ts.addRange(statements, ts.map(node.members, transformEnumMember));
- ts.addRange(statements, endLexicalEnvironment());
+ var members = ts.map(node.members, transformEnumMember);
+ ts.prependRange(statements, endLexicalEnvironment());
+ ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
/*multiLine*/ true);
@@ -59943,7 +60820,7 @@ var ts;
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -60480,7 +61357,7 @@ var ts;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -60752,7 +61629,7 @@ var ts;
var statements = [];
var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
@@ -60774,7 +61651,7 @@ var ts;
var declarations = endLexicalEnvironment();
if (ts.some(declarations)) {
var block = ts.convertToFunctionBody(expression);
- result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements));
+ result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
}
else {
result = expression;
@@ -60964,7 +61841,7 @@ var ts;
var enabledSubstitutions;
var enclosingFunctionFlags;
var enclosingSuperContainerFlags = 0;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -61042,9 +61919,14 @@ var ts;
return ts.visitEachChild(node, visitor, context);
}
function visitYieldExpression(node) {
- if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) {
- var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
- return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
+ if (node.asteriskToken) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ }
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
+ ? ts.visitNode(node.expression, visitor, ts.isExpression)
+ : ts.createVoidZero())), node), node);
}
return ts.visitEachChild(node, visitor, context);
}
@@ -61346,7 +62228,7 @@ var ts;
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
@@ -61371,11 +62253,11 @@ var ts;
statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
}
ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
- var trailingStatements = endLexicalEnvironment();
- if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) {
+ var leadingStatements = endLexicalEnvironment();
+ if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
+ ts.prependRange(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
- ts.addRange(statements, trailingStatements);
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
return body;
@@ -61533,7 +62415,7 @@ var ts;
var asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
- text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
+ text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
context.requestEmitHelper(awaitHelper);
@@ -61550,7 +62432,7 @@ var ts;
var asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
- text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };"
+ text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
context.requestEmitHelper(awaitHelper);
@@ -61561,7 +62443,7 @@ var ts;
var asyncValues = {
name: "typescript:asyncValues",
scoped: false,
- text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };"
+ text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
context.requestEmitHelper(asyncValues);
@@ -61575,7 +62457,7 @@ var ts;
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transform JSX-specific syntax in a SourceFile.
*
@@ -62083,7 +62965,7 @@ var ts;
(function (ts) {
function transformES2016(context) {
var hoistVariableDeclaration = context.hoistVariableDeclaration;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62291,7 +63173,7 @@ var ts;
* be reset.
*/
var enabledSubstitutions;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62467,7 +63349,7 @@ var ts;
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
}
@@ -62721,7 +63603,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -62834,7 +63716,7 @@ var ts;
&& !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
if (constructor) {
prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
@@ -63469,6 +64351,7 @@ var ts;
var expression = ts.visitNode(body, visitor, ts.isExpression);
var returnStatement = ts.createReturn(expression);
ts.setTextRange(returnStatement, body);
+ ts.moveSyntheticComments(returnStatement, body);
ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
statements.push(returnStatement);
// To align with the source map emit for the old emitter, we set a custom
@@ -63476,7 +64359,7 @@ var ts;
closeBraceLocation = body;
}
var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addRange(statements, lexicalEnvironment);
+ ts.prependRange(statements, lexicalEnvironment);
prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
// If we added any final generated statements, this must be a multi-line block
if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) {
@@ -64057,7 +64940,7 @@ var ts;
if (loopOutParameters.length) {
copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4);
}
- ts.addRange(statements_4, lexicalEnvironment);
+ ts.prependRange(statements_4, lexicalEnvironment);
loopBody = ts.createBlock(statements_4, /*multiline*/ true);
}
if (ts.isBlock(loopBody)) {
@@ -64510,10 +65393,12 @@ var ts;
// We skip any outer expressions in a number of places to get to the innermost
// expression, but we will restore them later to preserve comments and source maps.
var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
- // The class statements are the statements generated by visiting the first statement of the
+ // The class statements are the statements generated by visiting the first statement with initializer of the
// body (1), while all other statements are added to remainingStatements (2)
- var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1);
- var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1);
+ var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; };
+ var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
+ var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
+ var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement);
// We know there is only one variable declaration here as we verified this in an
// earlier call to isTypeScriptClassWrapper
@@ -64523,6 +65408,7 @@ var ts;
// we see as an assignment, for example:
//
// (function () {
+ // var C_1;
// var C = C_1 = (function () {
// function C() {
// }
@@ -64531,7 +65417,6 @@ var ts;
// }());
// C = C_1 = __decorate([dec], C);
// return C;
- // var C_1;
// }())
//
var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
@@ -65161,7 +66046,7 @@ var ts;
context.onSubstituteNode = onSubstituteNode;
context.enableSubstitution(184 /* PropertyAccessExpression */);
context.enableSubstitution(269 /* PropertyAssignment */);
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms an ES5 source file to ES3.
*
@@ -65473,7 +66358,7 @@ var ts;
var exceptionBlockStack; // A stack of containing exception blocks.
var currentExceptionBlock; // The current exception block.
var withBlockStack; // A stack containing `with` blocks.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
return node;
@@ -65730,7 +66615,7 @@ var ts;
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -67923,7 +68808,7 @@ var ts;
var currentModuleInfo; // The ExternalModuleInfo for the current file.
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
var needUMDDynamicImportHelper;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -67966,7 +68851,7 @@ var ts;
ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68189,7 +69074,7 @@ var ts;
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68211,7 +69096,7 @@ var ts;
*/
function addExportEqualsIfNeeded(statements, emitAsReturn) {
if (currentModuleInfo.exportEquals) {
- var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor);
+ var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
if (expressionResult) {
if (emitAsReturn) {
var statement = ts.createReturn(expressionResult);
@@ -68252,29 +69137,84 @@ var ts;
return visitFunctionDeclaration(node);
case 234 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 298 /* MergeDeclarationMarker */:
+ case 302 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 303 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
- function importCallExpressionVisitor(node) {
- // This visitor does not need to descend into the tree if there is no dynamic import,
+ function moduleExpressionElementVisitor(node) {
+ // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) {
+ if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
+ else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ return visitDestructuringAssignment(node);
+ }
else {
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
+ function destructuringNeedsFlattening(node) {
+ if (ts.isObjectLiteralExpression(node)) {
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var elem = _a[_i];
+ switch (elem.kind) {
+ case 269 /* PropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.initializer)) {
+ return true;
+ }
+ break;
+ case 270 /* ShorthandPropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.name)) {
+ return true;
+ }
+ break;
+ case 271 /* SpreadAssignment */:
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ break;
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return false;
+ default: ts.Debug.assertNever(elem, "Unhandled object member kind");
+ }
+ }
+ }
+ else if (ts.isArrayLiteralExpression(node)) {
+ for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
+ var elem = _c[_b];
+ if (ts.isSpreadElement(elem)) {
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ }
+ else if (destructuringNeedsFlattening(elem)) {
+ return true;
+ }
+ }
+ }
+ else if (ts.isIdentifier(node)) {
+ return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
+ }
+ return false;
+ }
+ function visitDestructuringAssignment(node) {
+ if (destructuringNeedsFlattening(node.left)) {
+ return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
+ }
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
+ }
function visitImportCallExpression(node) {
- var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor);
+ var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
@@ -68568,10 +69508,10 @@ var ts;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
else {
- statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
return ts.singleOrMany(statements);
}
@@ -68585,13 +69525,13 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor),
- /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)),
+ /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor),
+ /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)),
/*location*/ node),
/*original*/ node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68613,10 +69553,10 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node));
+ /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68661,7 +69601,7 @@ var ts;
}
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68673,6 +69613,21 @@ var ts;
}
return ts.singleOrMany(statements);
}
+ function createAllExportExpressions(name, value, location) {
+ var exportedNames = getExports(name);
+ if (exportedNames) {
+ // For each additional export of the declaration, apply an export assignment.
+ var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
+ for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
+ var exportName = exportedNames_1[_i];
+ // Mark the node to prevent triggering substitution.
+ ts.setEmitFlags(expression, 4 /* NoSubstitution */);
+ expression = createExportExpression(exportName, expression, /*location*/ location);
+ }
+ return expression;
+ }
+ return ts.createAssignment(name, value);
+ }
/**
* Transforms an exported variable with an initializer into an expression.
*
@@ -68680,13 +69635,13 @@ var ts;
*/
function transformInitializedVariable(node) {
if (ts.isBindingPattern(node.name)) {
- return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor),
+ return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor),
/*visitor*/ undefined, context, 0 /* All */,
- /*needsValue*/ false, createExportExpression);
+ /*needsValue*/ false, createAllExportExpressions);
}
else {
return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name),
- /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor));
+ /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor));
}
}
/**
@@ -69090,8 +70045,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
- var exportName = exportedNames_1[_i];
+ for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
+ var exportName = exportedNames_2[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression, /*location*/ node);
@@ -69127,8 +70082,8 @@ var ts;
? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)),
/*location*/ node)
: node;
- for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
- var exportName = exportedNames_2[_i];
+ for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
+ var exportName = exportedNames_3[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression);
@@ -69215,7 +70170,7 @@ var ts;
var hoistedStatements;
var enclosingBlockScopedContainer;
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -69388,7 +70343,7 @@ var ts;
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements);
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -69518,12 +70473,12 @@ var ts;
function createSettersArray(exportStarFunction, dependencyGroups) {
var setters = [];
for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
- var group_2 = dependencyGroups_1[_i];
+ var group_1 = dependencyGroups_1[_i];
// derive a unique name for parameter from the first named entry in the group
- var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
+ var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
var statements = [];
- for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
+ for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) {
var entry = _b[_a];
var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
@@ -70116,9 +71071,9 @@ var ts;
return visitCatchClause(node);
case 212 /* Block */:
return visitBlock(node);
- case 298 /* MergeDeclarationMarker */:
+ case 302 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 303 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -70551,8 +71506,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
- var exportName = exportedNames_3[_i];
+ for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
+ var exportName = exportedNames_4[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
return expression;
@@ -70585,8 +71540,8 @@ var ts;
var expression = node.kind === 198 /* PostfixUnaryExpression */
? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
: node;
- for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
- var exportName = exportedNames_4[_i];
+ for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
+ var exportName = exportedNames_5[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
if (node.kind === 198 /* PostfixUnaryExpression */) {
@@ -70653,7 +71608,7 @@ var ts;
context.enableEmitNotification(273 /* SourceFile */);
context.enableSubstitution(71 /* Identifier */);
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -71160,7 +72115,12 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */;
+ var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
+ 2048 /* WriteClassExpressionAsTypeLiteral */ |
+ 4096 /* UseTypeOfFunction */ |
+ 8 /* UseStructuralFallback */ |
+ 524288 /* AllowEmptyTuple */ |
+ 4 /* GenerateNamesForShadowedTypeParams */;
/**
* Transforms a ts file into a .d.ts file
* This process requires type information, which is retrieved through the emit resolver. Because of this,
@@ -71180,19 +72140,22 @@ var ts;
var lateMarkedStatements;
var lateStatementReplacementMap;
var suppressNewDiagnosticContexts;
+ var host = context.getEmitHost();
var symbolTracker = {
trackSymbol: trackSymbol,
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
- reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression
+ reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ moduleResolverHost: host,
+ trackReferencedAmbientModule: trackReferencedAmbientModule,
};
var errorNameNode;
var currentSourceFile;
+ var refs;
var resolver = context.getEmitResolver();
var options = context.getCompilerOptions();
var newLine = ts.getNewLineCharacter(options);
var noResolve = options.noResolve, stripInternal = options.stripInternal;
- var host = context.getEmitHost();
return transformRoot;
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
if (!typeReferenceDirectives) {
@@ -71204,6 +72167,10 @@ var ts;
necessaryTypeRefernces.set(ref, true);
}
}
+ function trackReferencedAmbientModule(node) {
+ var container = ts.getSourceFileOfNode(node);
+ refs.set("" + ts.getOriginalNodeId(container), container);
+ }
function handleSymbolAccessibilityError(symbolAccessibilityResult) {
if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
// Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
@@ -71234,6 +72201,8 @@ var ts;
}
}
function trackSymbol(symbol, enclosingDeclaration, meaning) {
+ if (symbol.flags & 262144 /* TypeParameter */)
+ return;
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
@@ -71277,12 +72246,16 @@ var ts;
resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
needsDeclare = false;
var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
return newFile;
}
needsDeclare = true;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ }), ts.mapDefined(node.prepends, function (prepend) {
+ if (prepend.kind === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.declarationText);
+ }
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -71305,13 +72278,13 @@ var ts;
lateMarkedStatements = undefined;
lateStatementReplacementMap = ts.createMap();
necessaryTypeRefernces = undefined;
- var refs = collectReferences(currentSourceFile, ts.createMap());
+ refs = collectReferences(currentSourceFile, ts.createMap());
var references = [];
var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
- refs.forEach(referenceVisitor);
var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
- var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements);
+ var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
+ refs.forEach(referenceVisitor);
var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements);
@@ -71323,17 +72296,19 @@ var ts;
}
function getFileReferenceForTypeName(typeName) {
// Elide type references for which we have imports
- for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
- var importStatement = emittedImports_1[_i];
- if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
- var expr = importStatement.moduleReference.expression;
- if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
+ if (emittedImports) {
+ for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
+ var importStatement = emittedImports_1[_i];
+ if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
+ var expr = importStatement.moduleReference.expression;
+ if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
+ return undefined;
+ }
+ }
+ else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
return undefined;
}
}
- else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
- return undefined;
- }
}
return { fileName: typeName, pos: -1, end: -1 };
}
@@ -71366,7 +72341,7 @@ var ts;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
if (elem) {
- ret.set("" + ts.getNodeId(elem), elem);
+ ret.set("" + ts.getOriginalNodeId(elem), elem);
}
});
return ret;
@@ -71583,7 +72558,7 @@ var ts;
}
// Nothing visible
}
- function filterCandidateImports(statements) {
+ function transformAndReplaceLatePaintedStatements(statements) {
// This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
// error handling which must now be included in the output and themselves checked for errors.
// For example:
@@ -71598,62 +72573,45 @@ var ts;
// In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
// be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
// dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
- var unconsideredStatements = [];
while (ts.length(lateMarkedStatements)) {
var i = lateMarkedStatements.shift();
- if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope
- unconsideredStatements.push(i);
- continue;
- }
if (!ts.isLateVisibilityPaintedStatement(i)) {
- return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
- }
- switch (i.kind) {
- case 242 /* ImportEqualsDeclaration */: {
- var result = transformImportEqualsDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 243 /* ImportDeclaration */: {
- var result = transformImportDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 213 /* VariableStatement */: {
- var result = transformVariableStatement(i, /*privateDeclaration*/ true); // Transform the statement (potentially again, possibly revealing more sub-nodes)
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- default: ts.Debug.assertNever(i, "Unhandled late painted statement!");
+ return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
}
+ var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true);
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
}
- // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not
- // be considered in the child scope
- lateMarkedStatements = unconsideredStatements;
// And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
// (and remove them from the set to examine for outter declarations)
return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
- }
- function visitLateVisibilityMarkedStatements(statement) {
- if (ts.isLateVisibilityPaintedStatement(statement)) {
- var key = "" + ts.getNodeId(statement);
- if (lateStatementReplacementMap.has(key)) {
- var result = lateStatementReplacementMap.get(key);
- lateStatementReplacementMap.delete(key);
- if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */)) {
- // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
- needsScopeFixMarker = true;
+ function visitLateVisibilityMarkedStatements(statement) {
+ if (ts.isLateVisibilityPaintedStatement(statement)) {
+ var key = "" + ts.getOriginalNodeId(statement);
+ if (lateStatementReplacementMap.has(key)) {
+ var result = lateStatementReplacementMap.get(key);
+ lateStatementReplacementMap.delete(key);
+ if (result && ts.isSourceFile(statement.parent)) {
+ if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) {
+ // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
+ needsScopeFixMarker = true;
+ }
+ if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) {
+ resultHasExternalModuleIndicator = true;
+ }
+ }
+ return result;
}
- return result;
}
- else {
- return ts.getParseTreeNode(statement) ? undefined : statement;
- }
- }
- else {
return statement;
}
}
+ function isExternalModuleIndicator(result) {
+ // Exported top-level member indicates moduleness
+ return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
+ }
+ function needsScopeMarker(result) {
+ return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
+ }
function visitDeclarationSubtree(input) {
if (shouldStripInternal(input))
return;
@@ -71851,13 +72809,21 @@ var ts;
return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
}
}
- case 242 /* ImportEqualsDeclaration */:
+ }
+ var result = transformTopLevelDeclaration(input);
+ // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
+ return input;
+ }
+ function transformTopLevelDeclaration(input, isPrivate) {
+ if (shouldStripInternal(input))
+ return;
+ switch (input.kind) {
+ case 242 /* ImportEqualsDeclaration */: {
+ return transformImportEqualsDeclaration(input);
+ }
case 243 /* ImportDeclaration */: {
- // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later
- // to reduce the likelihood we need to rewrite it
- lateMarkedStatements = lateMarkedStatements || [];
- ts.pushIfUnique(lateMarkedStatements, input);
- return input;
+ return transformImportDeclaration(input);
}
}
if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
@@ -71870,52 +72836,53 @@ var ts;
previousEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = input;
}
- var previousNeedsDeclare;
var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
var oldDiag = getSymbolAccessibilityDiagnostic;
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
}
- var oldPossibleImports;
+ var previousNeedsDeclare = needsDeclare;
switch (input.kind) {
case 236 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
return cleanup(ts.updateTypeAliasDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
case 235 /* InterfaceDeclaration */: {
return cleanup(ts.updateInterfaceDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
}
case 233 /* FunctionDeclaration */: {
// Generators lose their generator-ness, excepting their return type
return cleanup(ts.updateFunctionDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input),
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate),
/*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
/*body*/ undefined));
}
case 238 /* ModuleDeclaration */: {
- previousNeedsDeclare = needsDeclare;
needsDeclare = false;
- oldPossibleImports = lateMarkedStatements;
- lateMarkedStatements = undefined;
var inner = input.body;
if (inner && inner.kind === 239 /* ModuleBlock */) {
var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
- var body = ts.updateModuleBlock(inner, filterCandidateImports(statements));
+ var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements));
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
return cleanup(ts.updateModuleDeclaration(input,
/*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
}
else {
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
needsDeclare = false;
+ ts.visitNode(inner, visitDeclarationStatements);
+ // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
+ var id = "" + ts.getOriginalNodeId(inner);
+ var body = lateStatementReplacementMap.get(id);
+ lateStatementReplacementMap.delete(id);
return cleanup(ts.updateModuleDeclaration(input,
- /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements)));
+ /*decorators*/ undefined, mods, input.name, body));
}
}
case 234 /* ClassDeclaration */: {
- var modifiers = ts.createNodeArray(ensureModifiers(input));
+ var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate));
var typeParameters = ensureTypeParams(input, input.typeParameters);
var ctor = ts.getFirstConstructorWithBody(input);
var parameterProperties = void 0;
@@ -71985,12 +72952,10 @@ var ts;
}
}
case 213 /* VariableStatement */: {
- var result = transformVariableStatement(input);
- lateStatementReplacementMap.set("" + ts.getNodeId(input), result); // Don't actually elide yet; just leave as original node - will be elided/swapped by late pass
- return cleanup(input);
+ return cleanup(transformVariableStatement(input, isPrivate));
}
case 237 /* EnumDeclaration */: {
- return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
+ return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
if (shouldStripInternal(m))
return;
// Rewrite enum values to their constants, if available
@@ -72001,27 +72966,20 @@ var ts;
}
// Anything left unhandled is an error, so this should be unreachable
return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
- function cleanup(returnValue) {
+ function cleanup(node) {
if (isEnclosingDeclaration(input)) {
enclosingDeclaration = previousEnclosingDeclaration;
}
- if (input.kind === 238 /* ModuleDeclaration */) {
- needsDeclare = previousNeedsDeclare;
- lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements);
- }
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = oldDiag;
}
- if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) {
- if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) {
- // Exported top-level member indicates moduleness
- resultHasExternalModuleIndicator = true;
- }
+ if (input.kind === 238 /* ModuleDeclaration */) {
+ needsDeclare = previousNeedsDeclare;
}
- if (returnValue === input) {
- return returnValue;
+ if (node === input) {
+ return node;
}
- return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
+ return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
}
}
function transformVariableStatement(input, privateDeclaration) {
@@ -72098,7 +73056,7 @@ var ts;
return maskModifierFlags(node, mask, additions);
}
function ensureAccessor(node) {
- var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
+ var accessors = resolver.getAllAccessorDeclarations(node);
if (node.kind !== accessors.firstAccessor.kind) {
return;
}
@@ -72111,7 +73069,7 @@ var ts;
var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined);
var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile);
if (leadingsSyntheticCommentRanges) {
- var _loop_8 = function (range) {
+ var _loop_9 = function (range) {
if (range.kind === 3 /* MultiLineCommentTrivia */) {
var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2);
var lines = text.split(/\r\n?|\n/g);
@@ -72125,7 +73083,7 @@ var ts;
};
for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) {
var range = leadingsSyntheticCommentRanges_1[_i];
- _loop_8(range);
+ _loop_9(range);
}
}
return prop;
@@ -72287,7 +73245,7 @@ var ts;
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(300 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(304 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -72782,7 +73740,7 @@ var ts;
source = undefined;
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 299 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitPos(skipSourceTrivia(pos));
@@ -72799,7 +73757,7 @@ var ts;
}
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 299 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitPos(end);
@@ -72975,7 +73933,7 @@ var ts;
if (extendedDiagnostics) {
ts.performance.mark("preEmitNodeWithComment");
}
- var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 299 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */;
@@ -73299,6 +74257,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
+ var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
/*@internal*/
/**
@@ -73315,7 +74274,7 @@ var ts;
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles);
+ var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -73341,7 +74300,8 @@ var ts;
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
}
else {
var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options));
@@ -73350,17 +74310,27 @@ var ts;
var isJs = ts.isSourceFileJavaScript(sourceFile);
var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
+ function createDefaultBundleInfo() {
+ return {
+ originalOffset: -1,
+ totalLength: -1
+ };
+ }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
+ /* @internal */
function getOutputExtension(sourceFile, options) {
+ if (ts.isJsonSourceFile(sourceFile)) {
+ return ".json" /* Json */;
+ }
if (options.jsx === 1 /* Preserve */) {
if (ts.isSourceFileJavaScript(sourceFile)) {
if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
@@ -73374,9 +74344,10 @@ var ts;
}
return ".js" /* Js */;
}
+ ts.getOutputExtension = getOutputExtension;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -73390,6 +74361,7 @@ var ts;
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
+ var bundleInfo = createDefaultBundleInfo();
var emitSkipped = false;
// Emit each output file
ts.performance.mark("beforePrint");
@@ -73402,8 +74374,8 @@ var ts;
sourceMaps: sourceMapDataList
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
@@ -73415,10 +74387,12 @@ var ts;
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
+ if (bundleInfoPath) {
+ emittedFilesList.push(bundleInfoPath);
+ }
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
- var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
// Make sure not to write js file and source map file if any of them cannot be written
if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) {
emitSkipped = true;
@@ -73428,7 +74402,7 @@ var ts;
return;
}
// Transform the source files
- var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false);
+ var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false);
// Create a printer to print the nodes
var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), {
// resolver hooks
@@ -73443,7 +74417,8 @@ var ts;
// emitter hooks
onSetSourceFile: setSourceFile,
});
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap);
+ ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap);
// Clean up emit nodes on parse tree
transform.dispose();
}
@@ -73454,8 +74429,8 @@ var ts;
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
// Setup and perform the transformation to retrieve declarations from the input files
var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript);
- var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles;
- var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false);
+ var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
+ var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false);
if (ts.length(declarationTransform.diagnostics)) {
for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
var diagnostic = _b[_a];
@@ -73477,17 +74452,18 @@ var ts;
var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap);
+ ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap);
}
declarationTransform.dispose();
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) {
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) {
var bundle = sourceFileOrBundle.kind === 274 /* Bundle */ ? sourceFileOrBundle : undefined;
var sourceFile = sourceFileOrBundle.kind === 273 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList);
if (bundle) {
- printer.writeBundle(bundle, writer);
+ printer.writeBundle(bundle, writer, bundleInfo);
}
else {
printer.writeFile(sourceFile, writer);
@@ -73503,9 +74479,15 @@ var ts;
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles);
+ // Write bundled offset information if applicable
+ if (bundleInfoPath) {
+ bundleInfo.totalLength = writer.getTextPos();
+ ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
+ }
// Reset state
mapRecorder.reset();
writer.clear();
+ bundleInfo = createDefaultBundleInfo();
}
function setSourceFile(node) {
sourceMap.setSourceFile(node);
@@ -73515,6 +74497,13 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ var PipelinePhase;
+ (function (PipelinePhase) {
+ PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
+ PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments";
+ PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps";
+ PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit";
+ })(PipelinePhase || (PipelinePhase = {}));
function createPrinter(printerOptions, handlers) {
if (printerOptions === void 0) { printerOptions = {}; }
if (handlers === void 0) { handlers = {}; }
@@ -73572,6 +74561,7 @@ var ts;
switch (node.kind) {
case 273 /* SourceFile */: return printFile(node);
case 274 /* Bundle */: return printBundle(node);
+ case 275 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -73588,6 +74578,10 @@ var ts;
writeFile(sourceFile, beginPrint());
return endPrint();
}
+ function printUnparsedSource(unparsed) {
+ writeUnparsedSource(unparsed, beginPrint());
+ return endPrint();
+ }
function writeNode(hint, node, sourceFile, output) {
var previousWriter = writer;
setWriter(output);
@@ -73605,7 +74599,7 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, output) {
+ function writeBundle(bundle, output, bundleInfo) {
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output);
@@ -73613,13 +74607,28 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ writeLine();
+ }
+ if (bundleInfo) {
+ bundleInfo.originalOffset = writer.getTextPos();
+ }
+ for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
reset();
writer = previousWriter;
}
+ function writeUnparsedSource(unparsed, output) {
+ var previousWriter = writer;
+ setWriter(output);
+ print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
+ reset();
+ writer = previousWriter;
+ }
function writeFile(sourceFile, output) {
isOwnFileEmit = true;
var previousWriter = writer;
@@ -73642,7 +74651,8 @@ var ts;
if (sourceFile) {
setSourceFile(sourceFile);
}
- pipelineEmitWithNotification(hint, node);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, hint);
+ pipelinePhase(hint, node);
}
function setSourceFile(sourceFile) {
currentSourceFile = sourceFile;
@@ -73665,417 +74675,422 @@ var ts;
comments.reset();
setWriter(/*output*/ undefined);
}
- // TODO: Should this just be `emit`?
- // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034
- function emitIfPresent(node) {
- if (node) {
- emit(node);
- }
- }
function emit(node) {
- pipelineEmitWithNotification(4 /* Unspecified */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */);
+ pipelinePhase(4 /* Unspecified */, node);
}
function emitIdentifierName(node) {
- pipelineEmitWithNotification(2 /* IdentifierName */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */);
+ pipelinePhase(2 /* IdentifierName */, node);
}
function emitExpression(node) {
- pipelineEmitWithNotification(1 /* Expression */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */);
+ pipelinePhase(1 /* Expression */, node);
+ }
+ function getPipelinePhase(phase, hint) {
+ switch (phase) {
+ case 0 /* Notification */:
+ if (onEmitNode) {
+ return pipelineEmitWithNotification;
+ }
+ // falls through
+ case 1 /* Comments */:
+ if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
+ return pipelineEmitWithComments;
+ }
+ return pipelineEmitWithoutComments;
+ case 2 /* SourceMaps */:
+ if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
+ return pipelineEmitWithSourceMap;
+ }
+ // falls through
+ case 3 /* Emit */:
+ return pipelineEmitWithHint;
+ default:
+ return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase);
+ }
+ }
+ function getNextPipelinePhase(currentPhase, hint) {
+ return getPipelinePhase(currentPhase + 1, hint);
}
function pipelineEmitWithNotification(hint, node) {
- if (onEmitNode) {
- onEmitNode(hint, node, pipelineEmitWithComments);
- }
- else {
- pipelineEmitWithComments(hint, node);
- }
+ ts.Debug.assertDefined(onEmitNode);
+ onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint));
}
function pipelineEmitWithComments(hint, node) {
- node = trySubstituteNode(hint, node);
- if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
- emitNodeWithComments(hint, node, pipelineEmitWithSourceMap);
- }
- else {
- pipelineEmitWithSourceMap(hint, node);
- }
+ ts.Debug.assertDefined(emitNodeWithComments);
+ ts.Debug.assert(hint !== 0 /* SourceFile */);
+ emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint));
+ }
+ function pipelineEmitWithoutComments(hint, node) {
+ var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint);
+ pipelinePhase(hint, trySubstituteNode(hint, node));
}
function pipelineEmitWithSourceMap(hint, node) {
- if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
- onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
- }
- else {
- pipelineEmitWithHint(hint, node);
- }
+ ts.Debug.assertDefined(onEmitSourceMapOfNode);
+ ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */);
+ onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
}
function pipelineEmitWithHint(hint, node) {
- switch (hint) {
- case 0 /* SourceFile */: return pipelineEmitSourceFile(node);
- case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node);
- case 1 /* Expression */: return pipelineEmitExpression(node);
- case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
- case 4 /* Unspecified */: return pipelineEmitUnspecified(node);
+ if (hint === 0 /* SourceFile */)
+ return emitSourceFile(ts.cast(node, ts.isSourceFile));
+ if (hint === 2 /* IdentifierName */)
+ return emitIdentifier(ts.cast(node, ts.isIdentifier));
+ if (hint === 3 /* MappedTypeParameter */)
+ return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
+ if (hint === 4 /* Unspecified */) {
+ if (ts.isKeyword(node.kind))
+ return writeTokenNode(node, writeKeyword);
+ switch (node.kind) {
+ // Pseudo-literals
+ case 14 /* TemplateHead */:
+ case 15 /* TemplateMiddle */:
+ case 16 /* TemplateTail */:
+ return emitLiteral(node);
+ case 275 /* UnparsedSource */:
+ return emitUnparsedSource(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Parse tree nodes
+ // Names
+ case 145 /* QualifiedName */:
+ return emitQualifiedName(node);
+ case 146 /* ComputedPropertyName */:
+ return emitComputedPropertyName(node);
+ // Signature elements
+ case 147 /* TypeParameter */:
+ return emitTypeParameter(node);
+ case 148 /* Parameter */:
+ return emitParameter(node);
+ case 149 /* Decorator */:
+ return emitDecorator(node);
+ // Type members
+ case 150 /* PropertySignature */:
+ return emitPropertySignature(node);
+ case 151 /* PropertyDeclaration */:
+ return emitPropertyDeclaration(node);
+ case 152 /* MethodSignature */:
+ return emitMethodSignature(node);
+ case 153 /* MethodDeclaration */:
+ return emitMethodDeclaration(node);
+ case 154 /* Constructor */:
+ return emitConstructor(node);
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return emitAccessorDeclaration(node);
+ case 157 /* CallSignature */:
+ return emitCallSignature(node);
+ case 158 /* ConstructSignature */:
+ return emitConstructSignature(node);
+ case 159 /* IndexSignature */:
+ return emitIndexSignature(node);
+ // Types
+ case 160 /* TypePredicate */:
+ return emitTypePredicate(node);
+ case 161 /* TypeReference */:
+ return emitTypeReference(node);
+ case 162 /* FunctionType */:
+ return emitFunctionType(node);
+ case 283 /* JSDocFunctionType */:
+ return emitJSDocFunctionType(node);
+ case 163 /* ConstructorType */:
+ return emitConstructorType(node);
+ case 164 /* TypeQuery */:
+ return emitTypeQuery(node);
+ case 165 /* TypeLiteral */:
+ return emitTypeLiteral(node);
+ case 166 /* ArrayType */:
+ return emitArrayType(node);
+ case 167 /* TupleType */:
+ return emitTupleType(node);
+ case 168 /* UnionType */:
+ return emitUnionType(node);
+ case 169 /* IntersectionType */:
+ return emitIntersectionType(node);
+ case 170 /* ConditionalType */:
+ return emitConditionalType(node);
+ case 171 /* InferType */:
+ return emitInferType(node);
+ case 172 /* ParenthesizedType */:
+ return emitParenthesizedType(node);
+ case 206 /* ExpressionWithTypeArguments */:
+ return emitExpressionWithTypeArguments(node);
+ case 173 /* ThisType */:
+ return emitThisType();
+ case 174 /* TypeOperator */:
+ return emitTypeOperator(node);
+ case 175 /* IndexedAccessType */:
+ return emitIndexedAccessType(node);
+ case 176 /* MappedType */:
+ return emitMappedType(node);
+ case 177 /* LiteralType */:
+ return emitLiteralType(node);
+ case 178 /* ImportType */:
+ return emitImportTypeNode(node);
+ case 278 /* JSDocAllType */:
+ write("*");
+ return;
+ case 279 /* JSDocUnknownType */:
+ write("?");
+ return;
+ case 280 /* JSDocNullableType */:
+ return emitJSDocNullableType(node);
+ case 281 /* JSDocNonNullableType */:
+ return emitJSDocNonNullableType(node);
+ case 282 /* JSDocOptionalType */:
+ return emitJSDocOptionalType(node);
+ case 284 /* JSDocVariadicType */:
+ return emitJSDocVariadicType(node);
+ // Binding patterns
+ case 179 /* ObjectBindingPattern */:
+ return emitObjectBindingPattern(node);
+ case 180 /* ArrayBindingPattern */:
+ return emitArrayBindingPattern(node);
+ case 181 /* BindingElement */:
+ return emitBindingElement(node);
+ // Misc
+ case 210 /* TemplateSpan */:
+ return emitTemplateSpan(node);
+ case 211 /* SemicolonClassElement */:
+ return emitSemicolonClassElement();
+ // Statements
+ case 212 /* Block */:
+ return emitBlock(node);
+ case 213 /* VariableStatement */:
+ return emitVariableStatement(node);
+ case 214 /* EmptyStatement */:
+ return emitEmptyStatement();
+ case 215 /* ExpressionStatement */:
+ return emitExpressionStatement(node);
+ case 216 /* IfStatement */:
+ return emitIfStatement(node);
+ case 217 /* DoStatement */:
+ return emitDoStatement(node);
+ case 218 /* WhileStatement */:
+ return emitWhileStatement(node);
+ case 219 /* ForStatement */:
+ return emitForStatement(node);
+ case 220 /* ForInStatement */:
+ return emitForInStatement(node);
+ case 221 /* ForOfStatement */:
+ return emitForOfStatement(node);
+ case 222 /* ContinueStatement */:
+ return emitContinueStatement(node);
+ case 223 /* BreakStatement */:
+ return emitBreakStatement(node);
+ case 224 /* ReturnStatement */:
+ return emitReturnStatement(node);
+ case 225 /* WithStatement */:
+ return emitWithStatement(node);
+ case 226 /* SwitchStatement */:
+ return emitSwitchStatement(node);
+ case 227 /* LabeledStatement */:
+ return emitLabeledStatement(node);
+ case 228 /* ThrowStatement */:
+ return emitThrowStatement(node);
+ case 229 /* TryStatement */:
+ return emitTryStatement(node);
+ case 230 /* DebuggerStatement */:
+ return emitDebuggerStatement(node);
+ // Declarations
+ case 231 /* VariableDeclaration */:
+ return emitVariableDeclaration(node);
+ case 232 /* VariableDeclarationList */:
+ return emitVariableDeclarationList(node);
+ case 233 /* FunctionDeclaration */:
+ return emitFunctionDeclaration(node);
+ case 234 /* ClassDeclaration */:
+ return emitClassDeclaration(node);
+ case 235 /* InterfaceDeclaration */:
+ return emitInterfaceDeclaration(node);
+ case 236 /* TypeAliasDeclaration */:
+ return emitTypeAliasDeclaration(node);
+ case 237 /* EnumDeclaration */:
+ return emitEnumDeclaration(node);
+ case 238 /* ModuleDeclaration */:
+ return emitModuleDeclaration(node);
+ case 239 /* ModuleBlock */:
+ return emitModuleBlock(node);
+ case 240 /* CaseBlock */:
+ return emitCaseBlock(node);
+ case 241 /* NamespaceExportDeclaration */:
+ return emitNamespaceExportDeclaration(node);
+ case 242 /* ImportEqualsDeclaration */:
+ return emitImportEqualsDeclaration(node);
+ case 243 /* ImportDeclaration */:
+ return emitImportDeclaration(node);
+ case 244 /* ImportClause */:
+ return emitImportClause(node);
+ case 245 /* NamespaceImport */:
+ return emitNamespaceImport(node);
+ case 246 /* NamedImports */:
+ return emitNamedImports(node);
+ case 247 /* ImportSpecifier */:
+ return emitImportSpecifier(node);
+ case 248 /* ExportAssignment */:
+ return emitExportAssignment(node);
+ case 249 /* ExportDeclaration */:
+ return emitExportDeclaration(node);
+ case 250 /* NamedExports */:
+ return emitNamedExports(node);
+ case 251 /* ExportSpecifier */:
+ return emitExportSpecifier(node);
+ case 252 /* MissingDeclaration */:
+ return;
+ // Module references
+ case 253 /* ExternalModuleReference */:
+ return emitExternalModuleReference(node);
+ // JSX (non-expression)
+ case 10 /* JsxText */:
+ return emitJsxText(node);
+ case 256 /* JsxOpeningElement */:
+ case 259 /* JsxOpeningFragment */:
+ return emitJsxOpeningElementOrFragment(node);
+ case 257 /* JsxClosingElement */:
+ case 260 /* JsxClosingFragment */:
+ return emitJsxClosingElementOrFragment(node);
+ case 261 /* JsxAttribute */:
+ return emitJsxAttribute(node);
+ case 262 /* JsxAttributes */:
+ return emitJsxAttributes(node);
+ case 263 /* JsxSpreadAttribute */:
+ return emitJsxSpreadAttribute(node);
+ case 264 /* JsxExpression */:
+ return emitJsxExpression(node);
+ // Clauses
+ case 265 /* CaseClause */:
+ return emitCaseClause(node);
+ case 266 /* DefaultClause */:
+ return emitDefaultClause(node);
+ case 267 /* HeritageClause */:
+ return emitHeritageClause(node);
+ case 268 /* CatchClause */:
+ return emitCatchClause(node);
+ // Property assignments
+ case 269 /* PropertyAssignment */:
+ return emitPropertyAssignment(node);
+ case 270 /* ShorthandPropertyAssignment */:
+ return emitShorthandPropertyAssignment(node);
+ case 271 /* SpreadAssignment */:
+ return emitSpreadAssignment(node);
+ // Enum
+ case 272 /* EnumMember */:
+ return emitEnumMember(node);
+ // JSDoc nodes (ignored)
+ // Transformation nodes (ignored)
+ }
+ if (ts.isExpression(node)) {
+ hint = 1 /* Expression */;
+ node = trySubstituteNode(1 /* Expression */, node);
+ }
+ else if (ts.isToken(node)) {
+ return writeTokenNode(node, writePunctuation);
+ }
+ }
+ if (hint === 1 /* Expression */) {
+ switch (node.kind) {
+ // Literals
+ case 8 /* NumericLiteral */:
+ return emitNumericLiteral(node);
+ case 9 /* StringLiteral */:
+ case 12 /* RegularExpressionLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ return emitLiteral(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Reserved words
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ case 97 /* SuperKeyword */:
+ case 101 /* TrueKeyword */:
+ case 99 /* ThisKeyword */:
+ case 91 /* ImportKeyword */:
+ writeTokenNode(node, writeKeyword);
+ return;
+ // Expressions
+ case 182 /* ArrayLiteralExpression */:
+ return emitArrayLiteralExpression(node);
+ case 183 /* ObjectLiteralExpression */:
+ return emitObjectLiteralExpression(node);
+ case 184 /* PropertyAccessExpression */:
+ return emitPropertyAccessExpression(node);
+ case 185 /* ElementAccessExpression */:
+ return emitElementAccessExpression(node);
+ case 186 /* CallExpression */:
+ return emitCallExpression(node);
+ case 187 /* NewExpression */:
+ return emitNewExpression(node);
+ case 188 /* TaggedTemplateExpression */:
+ return emitTaggedTemplateExpression(node);
+ case 189 /* TypeAssertionExpression */:
+ return emitTypeAssertionExpression(node);
+ case 190 /* ParenthesizedExpression */:
+ return emitParenthesizedExpression(node);
+ case 191 /* FunctionExpression */:
+ return emitFunctionExpression(node);
+ case 192 /* ArrowFunction */:
+ return emitArrowFunction(node);
+ case 193 /* DeleteExpression */:
+ return emitDeleteExpression(node);
+ case 194 /* TypeOfExpression */:
+ return emitTypeOfExpression(node);
+ case 195 /* VoidExpression */:
+ return emitVoidExpression(node);
+ case 196 /* AwaitExpression */:
+ return emitAwaitExpression(node);
+ case 197 /* PrefixUnaryExpression */:
+ return emitPrefixUnaryExpression(node);
+ case 198 /* PostfixUnaryExpression */:
+ return emitPostfixUnaryExpression(node);
+ case 199 /* BinaryExpression */:
+ return emitBinaryExpression(node);
+ case 200 /* ConditionalExpression */:
+ return emitConditionalExpression(node);
+ case 201 /* TemplateExpression */:
+ return emitTemplateExpression(node);
+ case 202 /* YieldExpression */:
+ return emitYieldExpression(node);
+ case 203 /* SpreadElement */:
+ return emitSpreadExpression(node);
+ case 204 /* ClassExpression */:
+ return emitClassExpression(node);
+ case 205 /* OmittedExpression */:
+ return;
+ case 207 /* AsExpression */:
+ return emitAsExpression(node);
+ case 208 /* NonNullExpression */:
+ return emitNonNullExpression(node);
+ case 209 /* MetaProperty */:
+ return emitMetaProperty(node);
+ // JSX
+ case 254 /* JsxElement */:
+ return emitJsxElement(node);
+ case 255 /* JsxSelfClosingElement */:
+ return emitJsxSelfClosingElement(node);
+ case 258 /* JsxFragment */:
+ return emitJsxFragment(node);
+ // Transformation nodes
+ case 300 /* PartiallyEmittedExpression */:
+ return emitPartiallyEmittedExpression(node);
+ case 301 /* CommaListExpression */:
+ return emitCommaList(node);
+ }
}
- }
- function pipelineEmitSourceFile(node) {
- ts.Debug.assertNode(node, ts.isSourceFile);
- emitSourceFile(node);
- }
- function pipelineEmitIdentifierName(node) {
- ts.Debug.assertNode(node, ts.isIdentifier);
- emitIdentifier(node);
}
function emitMappedTypeParameter(node) {
emit(node.name);
writeSpace();
writeKeyword("in");
writeSpace();
- emitIfPresent(node.constraint);
- }
- function pipelineEmitUnspecified(node) {
- var kind = node.kind;
- // Reserved words
- // Strict mode reserved words
- // Contextual keywords
- if (ts.isKeyword(kind)) {
- writeTokenNode(node, writeKeyword);
- return;
- }
- switch (kind) {
- // Pseudo-literals
- case 14 /* TemplateHead */:
- case 15 /* TemplateMiddle */:
- case 16 /* TemplateTail */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Parse tree nodes
- // Names
- case 145 /* QualifiedName */:
- return emitQualifiedName(node);
- case 146 /* ComputedPropertyName */:
- return emitComputedPropertyName(node);
- // Signature elements
- case 147 /* TypeParameter */:
- return emitTypeParameter(node);
- case 148 /* Parameter */:
- return emitParameter(node);
- case 149 /* Decorator */:
- return emitDecorator(node);
- // Type members
- case 150 /* PropertySignature */:
- return emitPropertySignature(node);
- case 151 /* PropertyDeclaration */:
- return emitPropertyDeclaration(node);
- case 152 /* MethodSignature */:
- return emitMethodSignature(node);
- case 153 /* MethodDeclaration */:
- return emitMethodDeclaration(node);
- case 154 /* Constructor */:
- return emitConstructor(node);
- case 155 /* GetAccessor */:
- case 156 /* SetAccessor */:
- return emitAccessorDeclaration(node);
- case 157 /* CallSignature */:
- return emitCallSignature(node);
- case 158 /* ConstructSignature */:
- return emitConstructSignature(node);
- case 159 /* IndexSignature */:
- return emitIndexSignature(node);
- // Types
- case 160 /* TypePredicate */:
- return emitTypePredicate(node);
- case 161 /* TypeReference */:
- return emitTypeReference(node);
- case 162 /* FunctionType */:
- return emitFunctionType(node);
- case 281 /* JSDocFunctionType */:
- return emitJSDocFunctionType(node);
- case 163 /* ConstructorType */:
- return emitConstructorType(node);
- case 164 /* TypeQuery */:
- return emitTypeQuery(node);
- case 165 /* TypeLiteral */:
- return emitTypeLiteral(node);
- case 166 /* ArrayType */:
- return emitArrayType(node);
- case 167 /* TupleType */:
- return emitTupleType(node);
- case 168 /* UnionType */:
- return emitUnionType(node);
- case 169 /* IntersectionType */:
- return emitIntersectionType(node);
- case 170 /* ConditionalType */:
- return emitConditionalType(node);
- case 171 /* InferType */:
- return emitInferType(node);
- case 172 /* ParenthesizedType */:
- return emitParenthesizedType(node);
- case 206 /* ExpressionWithTypeArguments */:
- return emitExpressionWithTypeArguments(node);
- case 173 /* ThisType */:
- return emitThisType();
- case 174 /* TypeOperator */:
- return emitTypeOperator(node);
- case 175 /* IndexedAccessType */:
- return emitIndexedAccessType(node);
- case 176 /* MappedType */:
- return emitMappedType(node);
- case 177 /* LiteralType */:
- return emitLiteralType(node);
- case 178 /* ImportType */:
- return emitImportTypeNode(node);
- case 276 /* JSDocAllType */:
- write("*");
- return;
- case 277 /* JSDocUnknownType */:
- write("?");
- return;
- case 278 /* JSDocNullableType */:
- return emitJSDocNullableType(node);
- case 279 /* JSDocNonNullableType */:
- return emitJSDocNonNullableType(node);
- case 280 /* JSDocOptionalType */:
- return emitJSDocOptionalType(node);
- case 282 /* JSDocVariadicType */:
- return emitJSDocVariadicType(node);
- // Binding patterns
- case 179 /* ObjectBindingPattern */:
- return emitObjectBindingPattern(node);
- case 180 /* ArrayBindingPattern */:
- return emitArrayBindingPattern(node);
- case 181 /* BindingElement */:
- return emitBindingElement(node);
- // Misc
- case 210 /* TemplateSpan */:
- return emitTemplateSpan(node);
- case 211 /* SemicolonClassElement */:
- return emitSemicolonClassElement();
- // Statements
- case 212 /* Block */:
- return emitBlock(node);
- case 213 /* VariableStatement */:
- return emitVariableStatement(node);
- case 214 /* EmptyStatement */:
- return emitEmptyStatement();
- case 215 /* ExpressionStatement */:
- return emitExpressionStatement(node);
- case 216 /* IfStatement */:
- return emitIfStatement(node);
- case 217 /* DoStatement */:
- return emitDoStatement(node);
- case 218 /* WhileStatement */:
- return emitWhileStatement(node);
- case 219 /* ForStatement */:
- return emitForStatement(node);
- case 220 /* ForInStatement */:
- return emitForInStatement(node);
- case 221 /* ForOfStatement */:
- return emitForOfStatement(node);
- case 222 /* ContinueStatement */:
- return emitContinueStatement(node);
- case 223 /* BreakStatement */:
- return emitBreakStatement(node);
- case 224 /* ReturnStatement */:
- return emitReturnStatement(node);
- case 225 /* WithStatement */:
- return emitWithStatement(node);
- case 226 /* SwitchStatement */:
- return emitSwitchStatement(node);
- case 227 /* LabeledStatement */:
- return emitLabeledStatement(node);
- case 228 /* ThrowStatement */:
- return emitThrowStatement(node);
- case 229 /* TryStatement */:
- return emitTryStatement(node);
- case 230 /* DebuggerStatement */:
- return emitDebuggerStatement(node);
- // Declarations
- case 231 /* VariableDeclaration */:
- return emitVariableDeclaration(node);
- case 232 /* VariableDeclarationList */:
- return emitVariableDeclarationList(node);
- case 233 /* FunctionDeclaration */:
- return emitFunctionDeclaration(node);
- case 234 /* ClassDeclaration */:
- return emitClassDeclaration(node);
- case 235 /* InterfaceDeclaration */:
- return emitInterfaceDeclaration(node);
- case 236 /* TypeAliasDeclaration */:
- return emitTypeAliasDeclaration(node);
- case 237 /* EnumDeclaration */:
- return emitEnumDeclaration(node);
- case 238 /* ModuleDeclaration */:
- return emitModuleDeclaration(node);
- case 239 /* ModuleBlock */:
- return emitModuleBlock(node);
- case 240 /* CaseBlock */:
- return emitCaseBlock(node);
- case 241 /* NamespaceExportDeclaration */:
- return emitNamespaceExportDeclaration(node);
- case 242 /* ImportEqualsDeclaration */:
- return emitImportEqualsDeclaration(node);
- case 243 /* ImportDeclaration */:
- return emitImportDeclaration(node);
- case 244 /* ImportClause */:
- return emitImportClause(node);
- case 245 /* NamespaceImport */:
- return emitNamespaceImport(node);
- case 246 /* NamedImports */:
- return emitNamedImports(node);
- case 247 /* ImportSpecifier */:
- return emitImportSpecifier(node);
- case 248 /* ExportAssignment */:
- return emitExportAssignment(node);
- case 249 /* ExportDeclaration */:
- return emitExportDeclaration(node);
- case 250 /* NamedExports */:
- return emitNamedExports(node);
- case 251 /* ExportSpecifier */:
- return emitExportSpecifier(node);
- case 252 /* MissingDeclaration */:
- return;
- // Module references
- case 253 /* ExternalModuleReference */:
- return emitExternalModuleReference(node);
- // JSX (non-expression)
- case 10 /* JsxText */:
- return emitJsxText(node);
- case 256 /* JsxOpeningElement */:
- case 259 /* JsxOpeningFragment */:
- return emitJsxOpeningElementOrFragment(node);
- case 257 /* JsxClosingElement */:
- case 260 /* JsxClosingFragment */:
- return emitJsxClosingElementOrFragment(node);
- case 261 /* JsxAttribute */:
- return emitJsxAttribute(node);
- case 262 /* JsxAttributes */:
- return emitJsxAttributes(node);
- case 263 /* JsxSpreadAttribute */:
- return emitJsxSpreadAttribute(node);
- case 264 /* JsxExpression */:
- return emitJsxExpression(node);
- // Clauses
- case 265 /* CaseClause */:
- return emitCaseClause(node);
- case 266 /* DefaultClause */:
- return emitDefaultClause(node);
- case 267 /* HeritageClause */:
- return emitHeritageClause(node);
- case 268 /* CatchClause */:
- return emitCatchClause(node);
- // Property assignments
- case 269 /* PropertyAssignment */:
- return emitPropertyAssignment(node);
- case 270 /* ShorthandPropertyAssignment */:
- return emitShorthandPropertyAssignment(node);
- case 271 /* SpreadAssignment */:
- return emitSpreadAssignment(node);
- // Enum
- case 272 /* EnumMember */:
- return emitEnumMember(node);
- // JSDoc nodes (ignored)
- // Transformation nodes (ignored)
- }
- // If the node is an expression, try to emit it as an expression with
- // substitution.
- if (ts.isExpression(node)) {
- return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node));
- }
- if (ts.isToken(node)) {
- writeTokenNode(node, writePunctuation);
- return;
- }
- }
- function pipelineEmitExpression(node) {
- var kind = node.kind;
- switch (kind) {
- // Literals
- case 8 /* NumericLiteral */:
- return emitNumericLiteral(node);
- case 9 /* StringLiteral */:
- case 12 /* RegularExpressionLiteral */:
- case 13 /* NoSubstitutionTemplateLiteral */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Reserved words
- case 86 /* FalseKeyword */:
- case 95 /* NullKeyword */:
- case 97 /* SuperKeyword */:
- case 101 /* TrueKeyword */:
- case 99 /* ThisKeyword */:
- case 91 /* ImportKeyword */:
- writeTokenNode(node, writeKeyword);
- return;
- // Expressions
- case 182 /* ArrayLiteralExpression */:
- return emitArrayLiteralExpression(node);
- case 183 /* ObjectLiteralExpression */:
- return emitObjectLiteralExpression(node);
- case 184 /* PropertyAccessExpression */:
- return emitPropertyAccessExpression(node);
- case 185 /* ElementAccessExpression */:
- return emitElementAccessExpression(node);
- case 186 /* CallExpression */:
- return emitCallExpression(node);
- case 187 /* NewExpression */:
- return emitNewExpression(node);
- case 188 /* TaggedTemplateExpression */:
- return emitTaggedTemplateExpression(node);
- case 189 /* TypeAssertionExpression */:
- return emitTypeAssertionExpression(node);
- case 190 /* ParenthesizedExpression */:
- return emitParenthesizedExpression(node);
- case 191 /* FunctionExpression */:
- return emitFunctionExpression(node);
- case 192 /* ArrowFunction */:
- return emitArrowFunction(node);
- case 193 /* DeleteExpression */:
- return emitDeleteExpression(node);
- case 194 /* TypeOfExpression */:
- return emitTypeOfExpression(node);
- case 195 /* VoidExpression */:
- return emitVoidExpression(node);
- case 196 /* AwaitExpression */:
- return emitAwaitExpression(node);
- case 197 /* PrefixUnaryExpression */:
- return emitPrefixUnaryExpression(node);
- case 198 /* PostfixUnaryExpression */:
- return emitPostfixUnaryExpression(node);
- case 199 /* BinaryExpression */:
- return emitBinaryExpression(node);
- case 200 /* ConditionalExpression */:
- return emitConditionalExpression(node);
- case 201 /* TemplateExpression */:
- return emitTemplateExpression(node);
- case 202 /* YieldExpression */:
- return emitYieldExpression(node);
- case 203 /* SpreadElement */:
- return emitSpreadExpression(node);
- case 204 /* ClassExpression */:
- return emitClassExpression(node);
- case 205 /* OmittedExpression */:
- return;
- case 207 /* AsExpression */:
- return emitAsExpression(node);
- case 208 /* NonNullExpression */:
- return emitNonNullExpression(node);
- case 209 /* MetaProperty */:
- return emitMetaProperty(node);
- // JSX
- case 254 /* JsxElement */:
- return emitJsxElement(node);
- case 255 /* JsxSelfClosingElement */:
- return emitJsxSelfClosingElement(node);
- case 258 /* JsxFragment */:
- return emitJsxFragment(node);
- // Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
- return emitPartiallyEmittedExpression(node);
- case 297 /* CommaListExpression */:
- return emitCommaList(node);
- }
+ emit(node.constraint);
}
function trySubstituteNode(hint, node) {
return node && substituteNode && substituteNode(hint, node) || node;
@@ -74151,6 +75166,10 @@ var ts;
writeStringLiteral(text);
}
}
+ // SyntaxKind.UnparsedSource
+ function emitUnparsedSource(unparsed) {
+ write(unparsed.text);
+ }
//
// Identifiers
//
@@ -74201,13 +75220,11 @@ var ts;
function emitParameter(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.dotDotDotToken);
- if (node.name) {
- emitNodeWithWriter(node.name, writeParameter);
- }
- emitIfPresent(node.questionToken);
- if (node.parent && node.parent.kind === 281 /* JSDocFunctionType */ && !node.name) {
- emitIfPresent(node.type);
+ emit(node.dotDotDotToken);
+ emitNodeWithWriter(node.name, writeParameter);
+ emit(node.questionToken);
+ if (node.parent && node.parent.kind === 283 /* JSDocFunctionType */ && !node.name) {
+ emit(node.type);
}
else {
emitTypeAnnotation(node.type);
@@ -74226,7 +75243,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitNodeWithWriter(node.name, writeProperty);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeAnnotation(node.type);
writeSemicolon();
}
@@ -74234,28 +75251,30 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
- emitIfPresent(node.exclamationToken);
+ emit(node.questionToken);
+ emit(node.exclamationToken);
emitTypeAnnotation(node.type);
emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitMethodDeclaration(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitSignatureAndBody(node, emitSignatureHead);
}
function emitConstructor(node) {
@@ -74272,14 +75291,17 @@ var ts;
emitSignatureAndBody(node, emitSignatureHead);
}
function emitCallSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitConstructSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("new");
@@ -74288,6 +75310,7 @@ var ts;
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitIndexSignature(node) {
emitDecorators(node, node.decorators);
@@ -74314,18 +75337,20 @@ var ts;
emitTypeArguments(node, node.typeArguments);
}
function emitFunctionType(node) {
+ pushNameGenerationScope(node);
emitTypeParameters(node, node.typeParameters);
emitParametersForArrow(node, node.parameters);
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitJSDocFunctionType(node) {
write("function");
emitParameters(node, node.parameters);
write(":");
- emitIfPresent(node.type);
+ emit(node.type);
}
function emitJSDocNullableType(node) {
write("?");
@@ -74340,6 +75365,7 @@ var ts;
write("=");
}
function emitConstructorType(node) {
+ pushNameGenerationScope(node);
writeKeyword("new");
writeSpace();
emitTypeParameters(node, node.typeParameters);
@@ -74347,7 +75373,8 @@ var ts;
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitTypeQuery(node) {
writeKeyword("typeof");
@@ -74437,7 +75464,8 @@ var ts;
writeSpace();
}
writePunctuation("[");
- pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */);
+ pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter);
writePunctuation("]");
if (node.questionToken) {
emit(node.questionToken);
@@ -74447,7 +75475,7 @@ var ts;
}
writePunctuation(":");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
writeSemicolon();
if (emitFlags & 1 /* SingleLine */) {
writeSpace();
@@ -74490,7 +75518,7 @@ var ts;
writePunctuation("]");
}
function emitBindingElement(node) {
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
if (node.propertyName) {
emit(node.propertyName);
writePunctuation(":");
@@ -74508,6 +75536,7 @@ var ts;
emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine);
}
function emitObjectLiteralExpression(node) {
+ ts.forEach(node.properties, generateMemberNames);
var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
if (indentedFlag) {
increaseIndent();
@@ -74597,6 +75626,7 @@ var ts;
emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
+ generateNameIfNeeded(node.name);
emitFunctionDeclarationOrExpression(node);
}
function emitArrowFunction(node) {
@@ -74696,7 +75726,7 @@ var ts;
}
function emitYieldExpression(node) {
emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
@@ -74704,6 +75734,7 @@ var ts;
emitExpression(node.expression);
}
function emitClassExpression(node) {
+ generateNameIfNeeded(node.name);
emitClassDeclarationOrExpression(node);
}
function emitExpressionWithTypeArguments(node) {
@@ -74757,7 +75788,9 @@ var ts;
}
function emitExpressionStatement(node) {
emitExpression(node.expression);
- writeSemicolon();
+ if (!ts.isJsonSourceFile(currentSourceFile)) {
+ writeSemicolon();
+ }
}
function emitIfStatement(node) {
var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
@@ -74953,7 +75986,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("function");
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
writeSpace();
emitIdentifierName(node.name);
emitSignatureAndBody(node, emitSignatureHead);
@@ -74970,6 +76003,8 @@ var ts;
increaseIndent();
}
pushNameGenerationScope(node);
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
emitSignatureHead(node);
if (onEmitNode) {
onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
@@ -75065,6 +76100,7 @@ var ts;
emitClassDeclarationOrExpression(node);
}
function emitClassDeclarationOrExpression(node) {
+ ts.forEach(node.members, generateMemberNames);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("class");
@@ -75142,6 +76178,7 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
popNameGenerationScope(node);
}
@@ -75183,12 +76220,12 @@ var ts;
writeSemicolon();
}
function emitImportClause(node) {
- emitIfPresent(node.name);
+ emit(node.name);
if (node.name && node.namedBindings) {
emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
writeSpace();
}
- emitIfPresent(node.namedBindings);
+ emit(node.namedBindings);
}
function emitNamespaceImport(node) {
var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
@@ -75330,7 +76367,7 @@ var ts;
function emitJsxExpression(node) {
if (node.expression) {
writePunctuation("{");
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
emitExpression(node.expression);
writePunctuation("}");
}
@@ -75486,8 +76523,8 @@ var ts;
write("/// ");
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_17 = types; _d < types_17.length; _d++) {
+ var directive = types_17[_d];
write("/// ");
writeLine();
}
@@ -75495,6 +76532,7 @@ var ts;
function emitSourceFileWorker(node) {
var statements = node.statements;
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitHelpers(node);
var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
emitTripleSlashDirectivesIfNeeded(node);
@@ -75571,6 +76609,8 @@ var ts;
// Helpers
//
function emitNodeWithWriter(node, writer) {
+ if (!node)
+ return;
var savedWrite = write;
write = writer;
emit(node);
@@ -76060,7 +77100,7 @@ var ts;
if (ts.isGeneratedIdentifier(node)) {
return generateName(node);
}
- else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
+ else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
return ts.idText(node);
}
else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) {
@@ -76112,6 +77152,113 @@ var ts;
}
reservedNames.set(name, true);
}
+ function generateNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 212 /* Block */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 227 /* LabeledStatement */:
+ case 225 /* WithStatement */:
+ case 217 /* DoStatement */:
+ case 218 /* WhileStatement */:
+ generateNames(node.statement);
+ break;
+ case 216 /* IfStatement */:
+ generateNames(node.thenStatement);
+ generateNames(node.elseStatement);
+ break;
+ case 219 /* ForStatement */:
+ case 221 /* ForOfStatement */:
+ case 220 /* ForInStatement */:
+ generateNames(node.initializer);
+ generateNames(node.statement);
+ break;
+ case 226 /* SwitchStatement */:
+ generateNames(node.caseBlock);
+ break;
+ case 240 /* CaseBlock */:
+ ts.forEach(node.clauses, generateNames);
+ break;
+ case 265 /* CaseClause */:
+ case 266 /* DefaultClause */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 229 /* TryStatement */:
+ generateNames(node.tryBlock);
+ generateNames(node.catchClause);
+ generateNames(node.finallyBlock);
+ break;
+ case 268 /* CatchClause */:
+ generateNames(node.variableDeclaration);
+ generateNames(node.block);
+ break;
+ case 213 /* VariableStatement */:
+ generateNames(node.declarationList);
+ break;
+ case 232 /* VariableDeclarationList */:
+ ts.forEach(node.declarations, generateNames);
+ break;
+ case 231 /* VariableDeclaration */:
+ case 148 /* Parameter */:
+ case 181 /* BindingElement */:
+ case 234 /* ClassDeclaration */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 233 /* FunctionDeclaration */:
+ generateNameIfNeeded(node.name);
+ if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
+ }
+ break;
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 243 /* ImportDeclaration */:
+ generateNames(node.importClause);
+ break;
+ case 244 /* ImportClause */:
+ generateNameIfNeeded(node.name);
+ generateNames(node.namedBindings);
+ break;
+ case 245 /* NamespaceImport */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 246 /* NamedImports */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 247 /* ImportSpecifier */:
+ generateNameIfNeeded(node.propertyName || node.name);
+ break;
+ }
+ }
+ function generateMemberNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 269 /* PropertyAssignment */:
+ case 270 /* ShorthandPropertyAssignment */:
+ case 151 /* PropertyDeclaration */:
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ generateNameIfNeeded(node.name);
+ break;
+ }
+ }
+ function generateNameIfNeeded(name) {
+ if (name) {
+ if (ts.isGeneratedIdentifier(name)) {
+ generateName(name);
+ }
+ else if (ts.isBindingPattern(name)) {
+ generateNames(name);
+ }
+ }
+ }
/**
* Generate the text for a generated identifier.
*/
@@ -76119,17 +77266,7 @@ var ts;
if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
// Node names generate unique names based on their original node
// and are cached based on that node's id.
- if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) {
- var savedTempFlags = tempFlags;
- popNameGenerationScope(/*node*/ undefined);
- var result = generateNameCached(getNodeForGeneratedName(name));
- pushNameGenerationScope(/*node*/ undefined);
- tempFlags = savedTempFlags;
- return result;
- }
- else {
- return generateNameCached(getNodeForGeneratedName(name));
- }
+ return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
}
else {
// Auto, Loop, and Unique names are cached based on their unique
@@ -76138,9 +77275,9 @@ var ts;
return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
}
}
- function generateNameCached(node) {
+ function generateNameCached(node, flags) {
var nodeId = ts.getNodeId(node);
- return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node));
+ return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
}
/**
* Returns a value indicating whether a name is unique globally, within the current file,
@@ -76155,7 +77292,7 @@ var ts;
* Returns a value indicating whether a name is unique globally or within the current file.
*/
function isFileLevelUniqueName(name) {
- return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName);
+ return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
}
/**
* Returns a value indicating whether a name is unique within a container.
@@ -76212,11 +77349,16 @@ var ts;
* makeUniqueName are guaranteed to never conflict.
* If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
*/
- function makeUniqueName(baseName, checkFn, optimistic) {
+ function makeUniqueName(baseName, checkFn, optimistic, scoped) {
if (checkFn === void 0) { checkFn = isUniqueName; }
if (optimistic) {
if (checkFn(baseName)) {
- generatedNames.set(baseName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(baseName);
+ }
+ else {
+ generatedNames.set(baseName, true);
+ }
return baseName;
}
}
@@ -76228,7 +77370,12 @@ var ts;
while (true) {
var generatedName = baseName + i;
if (checkFn(generatedName)) {
- generatedNames.set(generatedName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(generatedName);
+ }
+ else {
+ generatedNames.set(generatedName, true);
+ }
return generatedName;
}
i++;
@@ -76275,10 +77422,10 @@ var ts;
/**
* Generates a unique name from a node.
*/
- function generateNameForNode(node) {
+ function generateNameForNode(node, flags) {
switch (node.kind) {
case 71 /* Identifier */:
- return makeUniqueName(getTextOfNode(node));
+ return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
case 238 /* ModuleDeclaration */:
case 237 /* EnumDeclaration */:
return generateNameForModuleOrEnum(node);
@@ -76305,11 +77452,11 @@ var ts;
function makeName(name) {
switch (name.autoGenerateFlags & 7 /* KindMask */) {
case 1 /* Auto */:
- return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 2 /* Loop */:
- return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 3 /* Unique */:
- return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32 /* Optimistic */));
+ return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
}
ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
}
@@ -76325,7 +77472,7 @@ var ts;
// if "node" is a different generated name (having a different
// "autoGenerateId"), use it and stop traversing.
if (ts.isIdentifier(node)
- && node.autoGenerateFlags === 4 /* Node */
+ && !!(node.autoGenerateFlags & 4 /* Node */)
&& node.autoGenerateId !== autoGenerateId) {
break;
}
@@ -76384,7 +77531,7 @@ var ts;
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function getCachedFileSystemEntries(rootDirPath) {
- return cachedReadDirectoryResult.get(rootDirPath);
+ return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
}
function getCachedFileSystemEntriesForBaseDir(path) {
return getCachedFileSystemEntries(ts.getDirectoryPath(path));
@@ -76397,7 +77544,7 @@ var ts;
files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
directories: host.getDirectories(rootDir) || []
};
- cachedReadDirectoryResult.set(rootDirPath, resultFromHost);
+ cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
return resultFromHost;
}
/**
@@ -76406,6 +77553,7 @@ var ts;
* The host request is done under try catch block to avoid caching incorrect result
*/
function tryReadDirectory(rootDir, rootDirPath) {
+ rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
var cachedResult = getCachedFileSystemEntries(rootDirPath);
if (cachedResult) {
return cachedResult;
@@ -76415,7 +77563,7 @@ var ts;
}
catch (_e) {
// If there is exception to read directories, dont cache the result and direct the calls to host
- ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath));
+ ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
return undefined;
}
}
@@ -76451,7 +77599,7 @@ var ts;
}
function directoryExists(dirPath) {
var path = toPath(dirPath);
- return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath);
+ return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
}
function createDirectory(dirPath) {
var path = toPath(dirPath);
@@ -76725,7 +77873,7 @@ var ts;
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
- return ts.getNormalizedPathFromPathComponents(commonPathComponents);
+ return ts.getPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
function createCompilerHost(options, setParentNodes) {
@@ -76832,7 +77980,8 @@ var ts;
directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); },
getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return ts.sys.getDirectories(path); },
- realpath: realpath
+ realpath: realpath,
+ readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }
};
}
ts.createCompilerHost = createCompilerHost;
@@ -76900,52 +78049,52 @@ var ts;
var output = "";
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
- var context = "";
+ var context_2 = "";
if (diagnostic.file) {
- var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file;
- var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
- var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
- var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
- var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
+ var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file;
+ var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character;
+ var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
+ var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line;
+ var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName;
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
for (var i = firstLine; i <= lastLine; i++) {
- context += host.getNewLine();
+ context_2 += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
- context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
}
- var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
- var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
- var lineContent = file.text.slice(lineStart, lineEnd);
+ var lineStart = ts.getPositionOfLineAndCharacter(file_9, i, 0);
+ var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_9, i + 1, 0) : file_9.text.length;
+ var lineContent = file_9.text.slice(lineStart, lineEnd);
lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
// Output the gutter and the actual contents of the line.
- context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += lineContent + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += lineContent + host.getNewLine();
// Output the gutter and the error span for the line using tildes.
- context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += ForegroundColorEscapeSequences.Red;
+ context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += ForegroundColorEscapeSequences.Red;
if (i === firstLine) {
// If we're on the last line, then limit it to the last character of the last line.
// Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
var lastCharForLine = i === lastLine ? lastLineChar : undefined;
- context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
- context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
+ context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
+ context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
}
else if (i === lastLine) {
- context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
+ context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~");
}
else {
// Squiggle the entire line.
- context += lineContent.replace(/./g, "~");
+ context_2 += lineContent.replace(/./g, "~");
}
- context += resetEscapeSequence;
+ context_2 += resetEscapeSequence;
}
output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan);
output += ":";
@@ -76959,7 +78108,7 @@ var ts;
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
output += host.getNewLine();
- output += context;
+ output += context_2;
}
output += host.getNewLine();
}
@@ -77069,21 +78218,19 @@ var ts;
oldOptions.baseUrl !== newOptions.baseUrl ||
!ts.equalOwnProperties(oldOptions.paths, newOptions.paths));
}
- /**
- * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions'
- * that represent a compilation unit.
- *
- * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and
- * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in.
- *
- * @param rootNames - A set of root files.
- * @param options - The compiler options which should be used.
- * @param host - The host interacts with the underlying file system.
- * @param oldProgram - Reuses an old program structure.
- * @param configFileParsingDiagnostics - error during config file parsing
- * @returns A 'Program' object.
- */
- function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ return {
+ rootNames: rootNames,
+ options: options,
+ host: host,
+ oldProgram: oldProgram,
+ configFileParsingDiagnostics: configFileParsingDiagnostics
+ };
+ }
+ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
+ var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions;
+ var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
+ var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram;
var program;
var files = [];
var commonSourceDirectory;
@@ -77111,6 +78258,7 @@ var ts;
var sourceFilesFoundSearchingNodeModules = ts.createMap();
ts.performance.mark("beforeProgram");
host = host || createCompilerHost(options);
+ var configParsingHost = parseConfigHostFromCompilerHost(host);
var skipDefaultLib = options.noLib;
var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
@@ -77120,6 +78268,7 @@ var ts;
// Map storing if there is emit blocking diagnostics for given input
var hasEmitBlockingDiagnostics = ts.createMap();
var _compilerOptionsObjectLiteralSyntax;
+ var _referencesArrayLiteralSyntax;
var moduleResolutionCache;
var resolveModuleNamesWorker;
var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
@@ -77159,6 +78308,23 @@ var ts;
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
+ // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
+ var resolvedProjectReferences = projectReferences ? [] : undefined;
+ var projectReferenceRedirects = ts.createMap();
+ if (projectReferences) {
+ for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) {
+ var ref = projectReferences_1[_i];
+ var parsedRef = parseProjectReferenceConfigFile(ref);
+ resolvedProjectReferences.push(parsedRef);
+ if (parsedRef) {
+ if (parsedRef.commandLine.options.outFile) {
+ var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts");
+ processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects);
+ }
+ }
+ }
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -77198,8 +78364,8 @@ var ts;
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) {
- var oldSourceFile = oldSourceFiles_1[_i];
+ for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
+ var oldSourceFile = oldSourceFiles_1[_a];
if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) {
host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions());
}
@@ -77240,6 +78406,7 @@ var ts;
isEmittedFile: isEmittedFile,
getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
+ getProjectReferences: getProjectReferences
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -77255,9 +78422,14 @@ var ts;
if (commonSourceDirectory === undefined) {
var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
- // If a rootDir is specified and is valid use it as the commonSourceDirectory
+ // If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
+ else if (options.composite) {
+ // Project compilations never infer their root from the input source paths
+ commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
+ checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
+ }
else {
commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
}
@@ -77295,16 +78467,16 @@ var ts;
// We only set `file.resolvedModules` via work from the current function,
// so it is defined iff we already called the current function on `file`.
// That call happened no later than the creation of the `file` object,
- // which per above occured during the current program creation.
+ // which per above occurred during the current program creation.
// Since we assume the filesystem does not change during program creation,
// it is safe to reuse resolutions from the earlier call.
- var result_3 = [];
+ var result_4 = [];
for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
var moduleName = moduleNames_1[_i];
var resolvedModule = file.resolvedModules.get(moduleName);
- result_3.push(resolvedModule);
+ result_4.push(resolvedModule);
}
- return result_3;
+ return result_4;
}
// At this point, we know at least one of the following hold:
// - file has local declarations for ambient modules
@@ -77435,6 +78607,34 @@ var ts;
if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
return oldProgram.structureIsReused = 0 /* Not */;
}
+ // Check if any referenced project tsconfig files are different
+ var oldRefs = oldProgram.getProjectReferences();
+ if (projectReferences) {
+ if (!oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ for (var i = 0; i < projectReferences.length; i++) {
+ var oldRef = oldRefs[i];
+ if (oldRef) {
+ var newRef = parseProjectReferenceConfigFile(projectReferences[i]);
+ if (!newRef || newRef.sourceFile !== oldRef.sourceFile) {
+ // Resolved project reference has gone missing or changed
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ else {
+ // A previously-unresolved reference may be resolved now
+ if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ }
+ }
+ else {
+ if (oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
// check if program source files has changed in the way that can affect structure of the program
var newSourceFiles = [];
var filePaths = [];
@@ -77602,6 +78802,7 @@ var ts;
}
function getEmitHost(writeFileCallback) {
return {
+ getPrependNodes: getPrependNodes,
getCanonicalFileName: getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
@@ -77615,6 +78816,32 @@ var ts;
isEmitBlocked: isEmitBlocked,
};
}
+ function getProjectReferences() {
+ if (!resolvedProjectReferences)
+ return;
+ return resolvedProjectReferences;
+ }
+ function getPrependNodes() {
+ if (!projectReferences) {
+ return ts.emptyArray;
+ }
+ var nodes = [];
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!resolvedRefOpts.options.outFile)
+ continue;
+ var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts");
+ var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n";
+ var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n";
+ var node = ts.createInputFiles(js, dts);
+ nodes.push(node);
+ }
+ }
+ return nodes;
+ }
function isSourceFileFromExternalLibrary(file) {
return sourceFilesFoundSearchingNodeModules.get(file.path);
}
@@ -77685,7 +78912,7 @@ var ts;
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -77769,9 +78996,9 @@ var ts;
var typeChecker = getDiagnosticsProducingTypeChecker();
ts.Debug.assert(!!sourceFile.bindDiagnostics);
var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
- // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins)
+ // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
- sourceFile.scriptKind === 5 /* External */ || isCheckJs;
+ sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */;
var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
@@ -78147,7 +79374,13 @@ var ts;
var sourceFile = getSourceFile(fileName);
if (fail) {
if (!sourceFile) {
- fail(ts.Diagnostics.File_0_not_found, fileName);
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
+ }
+ else {
+ fail(ts.Diagnostics.File_0_not_found, fileName);
+ }
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
@@ -78208,31 +79441,45 @@ var ts;
// Get source file from normalized fileName
function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) {
if (filesByName.has(path)) {
- var file_1 = filesByName.get(path);
+ var file_10 = filesByName.get(path);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
- if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
- reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
+ if (file_10 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_10.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
+ reportFileNamesDifferOnlyInCasingError(fileName, file_10.fileName, refFile, refPos, refEnd);
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
- if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) {
- sourceFilesFoundSearchingNodeModules.set(file_1.path, false);
+ if (file_10 && sourceFilesFoundSearchingNodeModules.get(file_10.path) && currentNodeModulesDepth === 0) {
+ sourceFilesFoundSearchingNodeModules.set(file_10.path, false);
if (!options.noResolve) {
- processReferencedFiles(file_1, isDefaultLib);
- processTypeReferenceDirectives(file_1);
+ processReferencedFiles(file_10, isDefaultLib);
+ processTypeReferenceDirectives(file_10);
}
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_10.path, false);
+ processImportedModules(file_10);
}
// See if we need to reprocess the imports due to prior skipped imports
- else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
+ else if (file_10 && modulesWithElidedImports.get(file_10.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_10.path, false);
+ processImportedModules(file_10);
}
}
- return file_1;
+ return file_10;
+ }
+ var redirectedPath;
+ if (refFile) {
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
+ fileName = redirect;
+ // Once we start redirecting to a file, we can potentially come back to it
+ // via a back-reference from another file in the .d.ts folder. If that happens we'll
+ // end up trying to add it to the program *again* because we were tracking it via its
+ // original (un-redirected) name. So we have to map both the original path and the redirected path
+ // to the source file we're about to find/create
+ redirectedPath = toPath(redirect);
+ }
}
// We haven't looked for this file, do so now and cache result
var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
@@ -78263,6 +79510,9 @@ var ts;
}
}
filesByName.set(path, file);
+ if (redirectedPath) {
+ filesByName.set(redirectedPath, file);
+ }
if (file) {
sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
file.path = path;
@@ -78293,6 +79543,22 @@ var ts;
}
return file;
}
+ function getProjectReferenceRedirect(fileName) {
+ var path = toPath(fileName);
+ // If this file is produced by a referenced project, we need to rewrite it to
+ // look in the output folder of the referenced project rather than the input
+ var normalized = ts.getNormalizedAbsolutePath(fileName, path);
+ var result;
+ projectReferenceRedirects.forEach(function (v, k) {
+ if (result !== undefined) {
+ return undefined;
+ }
+ if (normalized.indexOf(k) === 0) {
+ result = ts.changeExtension(fileName.replace(k, v), ".d.ts");
+ }
+ });
+ return result;
+ }
function processReferencedFiles(file, isDefaultLib) {
ts.forEach(file.referencedFiles, function (ref) {
var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
@@ -78302,6 +79568,9 @@ var ts;
function processTypeReferenceDirectives(file) {
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
+ if (!typeDirectives) {
+ return;
+ }
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName);
for (var i = 0; i < typeDirectives.length; i++) {
var ref = file.typeReferenceDirectives[i];
@@ -78381,7 +79650,7 @@ var ts;
continue;
}
var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
- var isJsFile = !ts.extensionIsTypeScript(resolution.extension);
+ var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension);
var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
var resolvedFileName = resolution.resolvedFileName;
if (isFromNodeModulesSearch) {
@@ -78423,9 +79692,9 @@ var ts;
function computeCommonSourceDirectory(sourceFiles) {
var fileNames = [];
for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
- var file = sourceFiles_2[_i];
- if (!file.isDeclarationFile) {
- fileNames.push(file.fileName);
+ var file_11 = sourceFiles_2[_i];
+ if (!file_11.isDeclarationFile) {
+ fileNames.push(file_11.fileName);
}
}
return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
@@ -78447,6 +79716,27 @@ var ts;
}
return allFilesBelongToPath;
}
+ function parseProjectReferenceConfigFile(ref) {
+ // The actual filename (i.e. add "/tsconfig.json" if necessary)
+ var refPath = resolveProjectReferencePath(host, ref);
+ // An absolute path pointing to the containing directory of the config file
+ var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
+ var sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
+ if (sourceFile === undefined) {
+ return undefined;
+ }
+ var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
+ return { commandLine: commandLine, sourceFile: sourceFile };
+ }
+ function addProjectReferenceRedirects(referencedProject, target) {
+ var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath));
+ target.set(rootDir, getDeclarationOutputDirectory(referencedProject));
+ }
+ function getDeclarationOutputDirectory(proj) {
+ return proj.options.declarationDir ||
+ proj.options.outDir ||
+ ts.getDirectoryPath(proj.options.configFilePath);
+ }
function verifyCompilerOptions() {
if (options.strictPropertyInitialization && !options.strictNullChecks) {
createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
@@ -78476,6 +79766,48 @@ var ts;
if (options.paths && options.baseUrl === undefined) {
createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
}
+ if (options.composite) {
+ if (options.declaration === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
+ }
+ }
+ if (projectReferences) {
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options;
+ if (resolvedRefOpts === undefined) {
+ createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path);
+ continue;
+ }
+ if (!resolvedRefOpts.composite) {
+ createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
+ }
+ if (ref.prepend) {
+ if (resolvedRefOpts.outFile) {
+ if (!host.fileExists(resolvedRefOpts.outFile)) {
+ createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path);
+ }
+ }
+ else {
+ createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
+ }
+ }
+ }
+ }
+ // List of collected files is complete; validate exhautiveness if this is a project with a file list
+ if (options.composite && rootNames.length < files.length) {
+ var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
+ var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); });
+ var _loop_10 = function (file_12) {
+ if (normalizedRootNames.every(function (r) { return r !== file_12; })) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_12));
+ }
+ };
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var file_12 = sourceFiles_4[_i];
+ _loop_10(file_12);
+ }
+ }
if (options.paths) {
for (var key in options.paths) {
if (!ts.hasProperty(options.paths, key)) {
@@ -78567,6 +79899,11 @@ var ts;
programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
}
}
+ if (options.resolveJsonModule) {
+ if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
+ }
+ }
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
@@ -78679,12 +80016,15 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
}
}
- function getOptionPathsSyntax() {
+ function getOptionsSyntaxByName(name) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
if (compilerOptionsObjectLiteralSyntax) {
- return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths");
+ return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
}
- return ts.emptyArray;
+ return undefined;
+ }
+ function getOptionPathsSyntax() {
+ return getOptionsSyntaxByName("paths") || ts.emptyArray;
}
function createDiagnosticForOptionName(message, option1, option2, option3) {
createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
@@ -78692,6 +80032,15 @@ var ts;
function createOptionValueDiagnostic(option1, message, arg0) {
createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
}
+ function createDiagnosticForReference(index, message, arg0, arg1) {
+ var referencesSyntax = getProjectReferencesSyntax();
+ if (referencesSyntax) {
+ if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) {
+ return;
+ }
+ }
+ programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
+ }
function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
@@ -78700,11 +80049,28 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
}
}
+ function getProjectReferencesSyntax() {
+ if (_referencesArrayLiteralSyntax === undefined) {
+ _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword
+ if (options.configFile) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (ts.isArrayLiteralExpression(prop.initializer)) {
+ _referencesArrayLiteralSyntax = prop.initializer;
+ break;
+ }
+ }
+ }
+ }
+ return _referencesArrayLiteralSyntax;
+ }
function getCompilerOptionsObjectLiteralSyntax() {
if (_compilerOptionsObjectLiteralSyntax === undefined) {
_compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword
- if (options.configFile && options.configFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ if (jsonObjectLiteral) {
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
var prop = _a[_i];
if (ts.isObjectLiteralExpression(prop.initializer)) {
_compilerOptionsObjectLiteralSyntax = prop.initializer;
@@ -78723,6 +80089,13 @@ var ts;
}
return !!props.length;
}
+ function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) {
+ if (arrayLiteral.elements.length <= index) {
+ // Out-of-bounds
+ return false;
+ }
+ programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2));
+ }
function blockEmittingOfFile(emitFileName, diag) {
hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
programDiagnostics.add(diag);
@@ -78759,6 +80132,27 @@ var ts;
}
ts.createProgram = createProgram;
/* @internal */
+ function parseConfigHostFromCompilerHost(host) {
+ return {
+ fileExists: function (f) { return host.fileExists(f); },
+ readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; },
+ readFile: function (f) { return host.readFile(f); },
+ useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ onUnRecoverableConfigFileDiagnostic: function () { return undefined; }
+ };
+ }
+ ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost;
+ /**
+ * Returns the target config filename of a project reference
+ */
+ function resolveProjectReferencePath(host, ref) {
+ if (!host.fileExists(ref.path)) {
+ return ts.combinePaths(ref.path, "tsconfig.json");
+ }
+ return ref.path;
+ }
+ /* @internal */
/**
* Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
* The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
@@ -78769,6 +80163,7 @@ var ts;
switch (extension) {
case ".ts" /* Ts */:
case ".d.ts" /* Dts */:
+ case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check
// These are always allowed.
return undefined;
case ".tsx" /* Tsx */:
@@ -78969,6 +80364,7 @@ var ts;
* Get all the dependencies of the sourceFile
*/
function getAllDependencies(state, programOfThisState, sourceFile) {
+ var _a;
var compilerOptions = programOfThisState.getCompilerOptions();
// With --out or --outFile all outputs go into single file, all files depend on each other
if (compilerOptions.outFile || compilerOptions.out) {
@@ -78988,7 +80384,7 @@ var ts;
var references = state.referencedMap.get(path);
if (references) {
var iterator = references.keys();
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
queue.push(value);
}
}
@@ -78998,7 +80394,6 @@ var ts;
var file = programOfThisState.getSourceFileByPath(path);
return file ? file.fileName : path;
}));
- var _b;
}
BuilderState.getAllDependencies = getAllDependencies;
/**
@@ -79443,8 +80838,8 @@ var ts;
}
var diagnostics;
for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_1 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
+ var sourceFile_2 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
@@ -79522,6 +80917,7 @@ var ts;
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
+ getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsOfFile: removeResolutionsOfFile,
invalidateResolutionOfFile: invalidateResolutionOfFile,
@@ -79694,6 +81090,10 @@ var ts;
function resolveModuleNames(moduleNames, containingFile, reusedNames) {
return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
}
+ function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
+ var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
+ return cache && cache.get(moduleName);
+ }
function isNodeModulesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules");
}
@@ -79741,17 +81141,19 @@ var ts;
return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath));
}
// Use some ancestor of the root directory
+ var subDirectory;
if (rootPath !== undefined) {
while (!isInDirectoryPath(dirPath, rootPath)) {
var parentPath = ts.getDirectoryPath(dirPath);
if (parentPath === dirPath) {
break;
}
+ subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length);
dirPath = parentPath;
dir = ts.getDirectoryPath(dir);
}
}
- return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath);
+ return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath);
}
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
@@ -79771,7 +81173,7 @@ var ts;
for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
// If the failed lookup location path is not one of the supported extensions,
// store it in the custom path
@@ -79783,7 +81185,7 @@ var ts;
setAtRoot = true;
}
else {
- setDirectoryWatcher(dir, dirPath);
+ setDirectoryWatcher(dir, dirPath, subDirectory);
}
}
}
@@ -79791,13 +81193,19 @@ var ts;
setDirectoryWatcher(rootDir, rootPath);
}
}
- function setDirectoryWatcher(dir, dirPath) {
+ function setDirectoryWatcher(dir, dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
if (dirWatcher) {
dirWatcher.refCount++;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 };
+ directoryWatchesOfFailedLookups.set(dirPath, dirWatcher);
+ }
+ if (subDirectory) {
+ var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap());
+ var existing = subDirectoryMap.get(subDirectory) || 0;
+ subDirectoryMap.set(subDirectory, existing + 1);
}
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
@@ -79813,7 +81221,7 @@ var ts;
for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
if (refCount) {
@@ -79829,7 +81237,7 @@ var ts;
removeAtRoot = true;
}
else {
- removeDirectoryWatcher(dirPath);
+ removeDirectoryWatcher(dirPath, subDirectory);
}
}
}
@@ -79837,22 +81245,40 @@ var ts;
removeDirectoryWatcher(rootPath);
}
}
- function removeDirectoryWatcher(dirPath) {
+ function removeDirectoryWatcher(dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (subDirectory) {
+ var existing = dirWatcher.subDirectoryMap.get(subDirectory);
+ if (existing === 1) {
+ dirWatcher.subDirectoryMap.delete(subDirectory);
+ }
+ else {
+ dirWatcher.subDirectoryMap.set(subDirectory, existing - 1);
+ }
+ }
// Do not close the watcher yet since it might be needed by other failed lookup locations.
dirWatcher.refCount--;
}
+ function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (!dirWatcher || !dirWatcher.subDirectoryMap)
+ return false;
+ return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) {
+ var fullSubDirectory = dirPath + "/" + subDirectory;
+ return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath);
+ });
+ }
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// If the files are added to project root or node_modules directory, always run through the invalidation process
// Otherwise run through invalidation only if adding to the immediate directory
if (!allFilesHaveInvalidatedResolution &&
- dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) {
+ (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) {
if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
resolutionHost.onInvalidatedResolution();
}
@@ -79976,7 +81402,7 @@ var ts;
return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// For now just recompile
@@ -80112,34 +81538,11 @@ var ts;
function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) {
var host = system;
host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); };
- var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
+ var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
host.onUnRecoverableConfigFileDiagnostic = undefined;
return result;
}
ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
- /**
- * Reads the config file, reports errors if any and exits if the config file cannot be found
- */
- function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
- var configFileText;
- try {
- configFileText = host.readFile(configFileName);
- }
- catch (e) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- if (!configFileText) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- var result = ts.parseJsonText(configFileName, configFileText);
- var cwd = host.getCurrentDirectory();
- return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
- }
- ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
*/
@@ -80221,12 +81624,12 @@ var ts;
watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; },
watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; },
setTimeout: system.setTimeout ? (function (callback, ms) {
+ var _a;
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args));
- var _a;
}) : ts.noop,
clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop,
trace: function (s) { return system.write(s); },
@@ -80986,6 +82389,13 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
+ {
+ name: "composite",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_project_compilation,
+ },
{
name: "removeComments",
type: "boolean",
@@ -81246,6 +82656,12 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "resolveJsonModule",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Include_modules_imported_with_json_extension
+ },
{
name: "listFiles",
type: "boolean",
@@ -81539,11 +82955,13 @@ var ts;
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
+ var projectReferences = undefined;
var errors = [];
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
errors: errors
};
function parseStrings(args) {
@@ -81656,6 +83074,29 @@ var ts;
}
return optionNameMap.get(optionName);
}
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
+ var configFileText;
+ try {
+ configFileText = host.readFile(configFileName);
+ }
+ catch (e) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ if (!configFileText) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ var result = ts.parseJsonText(configFileName, configFileText);
+ var cwd = host.getCurrentDirectory();
+ return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
+ }
+ ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -81703,55 +83144,67 @@ var ts;
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
if (_tsconfigRootOptions === undefined) {
- _tsconfigRootOptions = commandLineOptionsToMap([
- {
- name: "compilerOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
- },
- {
- name: "typingOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "typeAcquisition",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "extends",
- type: "string"
- },
- {
- name: "files",
- type: "list",
- element: {
+ _tsconfigRootOptions = {
+ name: undefined,
+ type: "object",
+ elementOptions: commandLineOptionsToMap([
+ {
+ name: "compilerOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
+ },
+ {
+ name: "typingOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "typeAcquisition",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "extends",
+ type: "string"
+ },
+ {
+ name: "references",
+ type: "list",
+ element: {
+ name: "references",
+ type: "object"
+ }
+ },
+ {
name: "files",
- type: "string"
- }
- },
- {
- name: "include",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "files",
+ type: "string"
+ }
+ },
+ {
name: "include",
- type: "string"
- }
- },
- {
- name: "exclude",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
+ }
+ },
+ {
name: "exclude",
- type: "string"
- }
- },
- ts.compileOnSaveCommandLineOption
- ]);
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
+ }
+ },
+ ts.compileOnSaveCommandLineOption
+ ])
+ };
}
return _tsconfigRootOptions;
}
@@ -81759,20 +83212,25 @@ var ts;
* Convert the json syntax tree into the json value
*/
function convertToObject(sourceFile, errors) {
- return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
}
ts.convertToObject = convertToObject;
/**
- * Convert the json syntax tree into the json value
+ * Convert the json syntax tree into the json value and report errors
+ * This returns the json value (apart from checking errors) only if returnValue provided is true.
+ * Otherwise it just checks the errors and returns undefined
*/
- function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) {
- if (!sourceFile.jsonObject) {
- return {};
+ /*@internal*/
+ function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
+ if (!sourceFile.statements.length) {
+ return returnValue ? {} : undefined;
+ }
+ return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
+ function isRootOptionMap(knownOptions) {
+ return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
}
- return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions,
- /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined);
function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
- var result = {};
+ var result = returnValue ? {} : undefined;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var element = _a[_i];
if (element.kind !== 269 /* PropertyAssignment */) {
@@ -81792,11 +83250,13 @@ var ts;
}
var value = convertPropertyValueToJson(element.initializer, option);
if (typeof keyText !== "undefined") {
- result[keyText] = value;
+ if (returnValue) {
+ result[keyText] = value;
+ }
// Notify key value set, if user asked for it
if (jsonConversionNotifier &&
// Current callbacks are only on known parent option or if we are setting values in the root
- (parentOption || knownOptions === knownRootOptions)) {
+ (parentOption || isRootOptionMap(knownOptions))) {
var isValidOptionValue = isCompilerOptionsValue(option, value);
if (parentOption) {
if (isValidOptionValue) {
@@ -81804,7 +83264,7 @@ var ts;
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
}
}
- else if (knownOptions === knownRootOptions) {
+ else if (isRootOptionMap(knownOptions)) {
if (isValidOptionValue) {
// Notify about the valid root key value being set
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
@@ -81820,7 +83280,7 @@ var ts;
return result;
}
function convertArrayLiteralExpressionToJson(elements, elementOption) {
- return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); });
}
function convertPropertyValueToJson(valueExpression, option) {
switch (valueExpression.kind) {
@@ -81895,6 +83355,7 @@ var ts;
return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
}
}
+ ts.convertToObjectWorker = convertToObjectWorker;
function getCompilerOptionValueTypeString(option) {
return option.type === "list" ?
"Array" :
@@ -81944,7 +83405,7 @@ var ts;
function serializeCompilerOptions(options) {
var result = ts.createMap();
var optionsNameMap = getOptionNameMap().optionNameMap;
- var _loop_9 = function (name) {
+ var _loop_11 = function (name) {
if (ts.hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
@@ -81973,7 +83434,7 @@ var ts;
}
};
for (var name in options) {
- _loop_9(name);
+ _loop_11(name);
}
return result;
}
@@ -82123,12 +83584,13 @@ var ts;
var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
var raw = parsedConfig.raw;
var options = ts.extend(existingOptions, parsedConfig.options || {});
- options.configFilePath = configFileName;
+ options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
setConfigFileInOptions(options, sourceFile);
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
+ var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences;
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
raw: raw,
errors: errors,
@@ -82167,19 +83629,43 @@ var ts;
createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
}
}
- else {
- var outDir = raw.compilerOptions && raw.compilerOptions.outDir;
- if (outDir) {
- excludeSpecs = [outDir];
+ else if (raw.compilerOptions) {
+ var outDir = raw.compilerOptions.outDir;
+ var declarationDir = raw.compilerOptions.declarationDir;
+ if (outDir || declarationDir) {
+ excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
}
}
if (filesSpecs === undefined && includeSpecs === undefined) {
includeSpecs = ["**/*"];
}
var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) {
+ if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) {
errors.push(getErrorForNoInputFiles(result.spec, configFileName));
}
+ if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
+ if (ts.isArray(raw.references)) {
+ var references = [];
+ for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
+ var ref = _a[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ references.push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
+ }
+ }
+ result.projectReferences = references;
+ }
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
+ }
+ }
return result;
}
function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
@@ -82297,7 +83783,7 @@ var ts;
}
}
};
- var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator);
+ var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
if (!typeAcquisition) {
if (typingOptionstypeAcquisition) {
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
@@ -82332,6 +83818,7 @@ var ts;
return extendedConfigPath;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
+ var _a;
var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (sourceFile) {
(sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName);
@@ -82360,7 +83847,6 @@ var ts;
mapPropertiesInRawIfNotUndefined("files");
}
return extendedConfig;
- var _a;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
@@ -82385,7 +83871,7 @@ var ts;
}
ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
function getDefaultCompilerOptions(configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
+ var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
: {};
return options;
@@ -82393,10 +83879,13 @@ var ts;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultCompilerOptions(configFileName);
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
+ if (configFileName) {
+ options.configFilePath = ts.normalizeSlashes(configFileName);
+ }
return options;
}
function getDefaultTypeAcquisition(configFileName) {
- return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
+ return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultTypeAcquisition(configFileName);
@@ -82557,7 +84046,7 @@ var ts;
// or a recursive directory. This information is used by filesystem watchers to monitor for
// new entries in these paths.
var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
- var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
+ var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
}
/**
@@ -82591,37 +84080,41 @@ var ts;
if (filesSpecs) {
for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
var fileName = filesSpecs_1[_i];
- var file = ts.getNormalizedAbsolutePath(fileName, basePath);
- literalFileMap.set(keyMapper(file), file);
+ var file_13 = ts.getNormalizedAbsolutePath(fileName, basePath);
+ literalFileMap.set(keyMapper(file_13), file_13);
}
}
if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
- var file = _b[_a];
+ var file_14 = _b[_a];
// If we have already included a literal or wildcard path with a
// higher priority extension, we should skip this file.
//
// This handles cases where we may encounter both .ts and
// .d.ts (or .js if "allowJs" is enabled) in the same
// directory when they are compilation outputs.
- if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
+ if (hasFileWithHigherPriorityExtension(file_14, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
continue;
}
// We may have included a wildcard path with a lower priority
// extension due to the user-defined order of entries in the
// "include" array. If there is a lower priority extension in the
// same directory, we should remove it.
- removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
- var key = keyMapper(file);
+ removeWildcardFilesWithLowerPriorityExtension(file_14, wildcardFileMap, supportedExtensions, keyMapper);
+ var key = keyMapper(file_14);
if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
- wildcardFileMap.set(key, file);
+ wildcardFileMap.set(key, file_14);
}
}
}
var literalFiles = ts.arrayFrom(literalFileMap.values());
var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
+ var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) {
+ return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) });
+ });
return {
fileNames: literalFiles.concat(wildcardFiles),
+ projectReferences: projectReferences,
wildcardDirectories: wildcardDirectories,
spec: spec
};
@@ -82636,20 +84129,10 @@ var ts;
return diag === undefined;
});
function createDiagnostic(message, spec) {
- if (jsonSourceFile && jsonSourceFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) {
- var property = _a[_i];
- if (ts.isArrayLiteralExpression(property.initializer)) {
- for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) {
- var element = _c[_b];
- if (ts.isStringLiteral(element) && element.text === spec) {
- return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec);
- }
- }
- }
- }
- }
- return ts.createCompilerDiagnostic(message, spec);
+ var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
+ return element ?
+ ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
+ ts.createCompilerDiagnostic(message, spec);
}
}
function specToDiagnostic(spec, allowTrailingRecursion) {
@@ -82682,8 +84165,8 @@ var ts;
if (include !== undefined) {
var recursiveKeys = [];
for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
- var file = include_1[_i];
- var spec = ts.normalizePath(ts.combinePaths(path, file));
+ var file_15 = include_1[_i];
+ var spec = ts.normalizePath(ts.combinePaths(path, file_15));
if (excludeRegex && excludeRegex.test(spec)) {
continue;
}
@@ -82877,6 +84360,17 @@ var ts;
SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
})(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
+ var OutliningSpanKind;
+ (function (OutliningSpanKind) {
+ /** Single or multi-line comments */
+ OutliningSpanKind["Comment"] = "comment";
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ OutliningSpanKind["Region"] = "region";
+ /** Declarations and expressions */
+ OutliningSpanKind["Code"] = "code";
+ /** Contiguous blocks of import declarations */
+ OutliningSpanKind["Imports"] = "imports";
+ })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
var OutputFileType;
(function (OutputFileType) {
OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
@@ -82972,6 +84466,8 @@ var ts;
*
*/
ScriptElementKind["jsxAttribute"] = "JSX attribute";
+ /** String literal */
+ ScriptElementKind["string"] = "string";
})(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
var ScriptElementKindModifier;
(function (ScriptElementKindModifier) {
@@ -83077,7 +84573,7 @@ var ts;
case 236 /* TypeAliasDeclaration */:
case 165 /* TypeLiteral */:
return 2 /* Type */;
- case 292 /* JSDocTypedefTag */:
+ case 296 /* JSDocTypedefTag */:
// If it has no name node, it shares the name with the value declaration below it.
return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
case 272 /* EnumMember */:
@@ -83131,6 +84627,10 @@ var ts;
ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName
return 2 /* Type */;
}
+ else if (ts.isLiteralTypeNode(node.parent)) {
+ // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings.
+ return 2 /* Type */ | 1 /* Value */;
+ }
else {
return 1 /* Value */;
}
@@ -83193,6 +84693,8 @@ var ts;
switch (node.parent.kind) {
case 161 /* TypeReference */:
return true;
+ case 178 /* ImportType */:
+ return !node.parent.isTypeOf;
case 206 /* ExpressionWithTypeArguments */:
return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
}
@@ -83280,7 +84782,7 @@ var ts;
}
ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
function getContainerNode(node) {
- if (node.kind === 292 /* JSDocTypedefTag */) {
+ if (ts.isJSDocTypeAlias(node)) {
// This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
// node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
// Then we get parent again in the loop.
@@ -83318,7 +84820,10 @@ var ts;
case 204 /* ClassExpression */:
return "class" /* classElement */;
case 235 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
- case 236 /* TypeAliasDeclaration */: return "type" /* typeElement */;
+ case 236 /* TypeAliasDeclaration */:
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ return "type" /* typeElement */;
case 237 /* EnumDeclaration */: return "enum" /* enumElement */;
case 231 /* VariableDeclaration */:
return getKindOfVariableDeclaration(node);
@@ -83349,8 +84854,6 @@ var ts;
case 251 /* ExportSpecifier */:
case 245 /* NamespaceImport */:
return "alias" /* alias */;
- case 292 /* JSDocTypedefTag */:
- return "type" /* typeElement */;
case 199 /* BinaryExpression */:
var kind = ts.getSpecialPropertyAssignmentKind(node);
var right = node.right;
@@ -83412,6 +84915,10 @@ var ts;
return startEndContainsRange(r1.pos, r1.end, r2);
}
ts.rangeContainsRange = rangeContainsRange;
+ function rangeContainsPosition(r, pos) {
+ return r.pos <= pos && pos <= r.end;
+ }
+ ts.rangeContainsPosition = rangeContainsPosition;
function startEndContainsRange(start, end, range) {
return start <= range.pos && end >= range.end;
}
@@ -83678,7 +85185,7 @@ var ts;
return findPrecedingToken(position, file);
}
ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
- function findNextToken(previousToken, parent) {
+ function findNextToken(previousToken, parent, sourceFile) {
return find(parent);
function find(n) {
if (ts.isToken(n) && n.pos === previousToken.end) {
@@ -83693,7 +85200,7 @@ var ts;
(child.pos <= previousToken.pos && child.end > previousToken.end) ||
// previous token ends exactly at the beginning of child
(child.pos === previousToken.end);
- if (shouldDiveInChildNode && nodeHasTokens(child)) {
+ if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) {
return find(child);
}
}
@@ -83724,11 +85231,11 @@ var ts;
if (position < child.end) {
var start = child.getStart(sourceFile, includeJsDoc);
var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
- !nodeHasTokens(child) ||
+ !nodeHasTokens(child, sourceFile) ||
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
else {
@@ -83743,7 +85250,7 @@ var ts;
// Try to find the rightmost token in the file without filtering.
// Namely we are skipping the check: 'position < node.end'
if (children.length) {
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
}
@@ -83757,19 +85264,19 @@ var ts;
return n;
}
var children = n.getChildren(sourceFile);
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
/**
* Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
*/
- function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) {
+ function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
var child = children[i];
if (isWhiteSpaceOnlyJsxText(child)) {
ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
}
- else if (nodeHasTokens(children[i])) {
+ else if (nodeHasTokens(children[i], sourceFile)) {
return children[i];
}
}
@@ -83881,22 +85388,22 @@ var ts;
remainingLessThanTokens++;
break;
case 18 /* CloseBraceToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile);
if (!token)
return false;
break;
case 20 /* CloseParenToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile);
if (!token)
return false;
break;
case 22 /* CloseBracketToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile);
if (!token)
return false;
@@ -83950,10 +85457,10 @@ var ts;
}
}
ts.hasDocComment = hasDocComment;
- function nodeHasTokens(n) {
+ function nodeHasTokens(n, sourceFile) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note: getWidth() does not take trivia into account.
- return n.getWidth() !== 0;
+ return n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node) {
var flags = ts.getCombinedModifierFlags(node);
@@ -84050,11 +85557,6 @@ var ts;
return false;
}
ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
- function hasTrailingDirectorySeparator(path) {
- var lastCharacter = path.charAt(path.length - 1);
- return lastCharacter === "/" || lastCharacter === "\\";
- }
- ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function isInReferenceComment(sourceFile, position) {
return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) {
var commentText = sourceFile.text.substring(c.pos, c.end);
@@ -84077,6 +85579,10 @@ var ts;
return ts.createTextSpanFromBounds(range.pos, range.end);
}
ts.createTextSpanFromRange = createTextSpanFromRange;
+ function createTextRangeFromSpan(span) {
+ return ts.createTextRange(span.start, span.start + span.length);
+ }
+ ts.createTextRangeFromSpan = createTextRangeFromSpan;
function createTextChangeFromStartLength(start, length, newText) {
return createTextChange(ts.createTextSpan(start, length), newText);
}
@@ -84109,7 +85615,6 @@ var ts;
return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
}
ts.isExternalModuleSymbol = isExternalModuleSymbol;
- /** Returns `true` the first time it encounters a node and `false` afterwards. */
function nodeSeenTracker() {
var seen = [];
return function (node) {
@@ -84157,6 +85662,63 @@ var ts;
return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
}
ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
+ function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) {
+ return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined;
+ }
+ ts.makeImportIfNecessary = makeImportIfNecessary;
+ function makeImport(defaultImport, namedImports, moduleSpecifier) {
+ return ts.createImportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, defaultImport || namedImports
+ ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined)
+ : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier);
+ }
+ ts.makeImport = makeImport;
+ function symbolNameNoDefault(symbol) {
+ var escaped = symbolEscapedNameNoDefault(symbol);
+ return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
+ }
+ ts.symbolNameNoDefault = symbolNameNoDefault;
+ function symbolEscapedNameNoDefault(symbol) {
+ if (symbol.escapedName !== "default" /* Default */) {
+ return symbol.escapedName;
+ }
+ return ts.firstDefined(symbol.declarations, function (decl) {
+ var name = ts.getNameOfDeclaration(decl);
+ return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined;
+ });
+ }
+ ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
+ function getPropertySymbolFromBindingElement(checker, bindingElement) {
+ var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
+ var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
+ if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
+ // See GH#16922
+ ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
+ return propSymbol.target;
+ }
+ return propSymbol;
+ }
+ ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
+ var NodeSet = /** @class */ (function () {
+ function NodeSet() {
+ this.map = ts.createMap();
+ }
+ NodeSet.prototype.add = function (node) {
+ this.map.set(String(ts.getNodeId(node)), node);
+ };
+ NodeSet.prototype.has = function (node) {
+ return this.map.has(String(ts.getNodeId(node)));
+ };
+ NodeSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ NodeSet.prototype.some = function (pred) {
+ return ts.forEachEntry(this.map, pred) || false;
+ };
+ return NodeSet;
+ }());
+ ts.NodeSet = NodeSet;
})(ts || (ts = {}));
// Display-part writer helpers
/* @internal */
@@ -84489,20 +86051,20 @@ var ts;
* user was before extracting it.
*/
/* @internal */
- function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) {
+ function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
var delta = 0;
var lastPos = -1;
for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
- var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
+ var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
ts.Debug.assert(fileName === renameFilename);
- for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) {
- var change = textChanges_2[_b];
+ for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
+ var change = textChanges_1[_b];
var span = change.span, newText = change.newText;
var index = newText.indexOf(name);
if (index !== -1) {
lastPos = span.start + delta + index;
// If the reference comes first, return immediately.
- if (!isDeclaredBeforeUse) {
+ if (!preferLastLocation) {
return lastPos;
}
}
@@ -84510,7 +86072,7 @@ var ts;
}
}
// If the declaration comes first, return the position of the last occurrence.
- ts.Debug.assert(isDeclaredBeforeUse);
+ ts.Debug.assert(preferLastLocation);
ts.Debug.assert(lastPos >= 0);
return lastPos;
}
@@ -85158,20 +86720,22 @@ 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 288 /* JSDocParameterTag */:
+ case 292 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
+ pos = tag.end;
break;
- case 290 /* JSDocTypeTag */:
+ case 294 /* JSDocTypeTag */:
processElement(tag.typeExpression);
+ pos = tag.end;
break;
- case 289 /* JSDocReturnTag */:
+ case 293 /* JSDocReturnTag */:
processElement(tag.typeExpression);
+ pos = tag.end;
break;
}
- pos = tag.end;
}
}
if (pos !== docComment.end) {
@@ -85413,7 +86977,7 @@ var ts;
var scriptPath = node.getSourceFile().path;
var scriptDirectory = ts.getDirectoryPath(scriptPath);
if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) {
- var extensions = ts.getSupportedExtensions(compilerOptions);
+ var extensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (compilerOptions.rootDirs) {
return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath);
}
@@ -85426,6 +86990,12 @@ var ts;
return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
}
}
+ function getSupportedExtensionsForModuleResolution(compilerOptions) {
+ var extensions = ts.getSupportedExtensions(compilerOptions);
+ return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
+ extensions.concat(".json" /* Json */) :
+ extensions;
+ }
/**
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
@@ -85464,13 +87034,16 @@ var ts;
* Remove the basename from the path. Note that we don't use the basename to filter completions;
* the client is responsible for refining completions.
*/
- fragment = ts.getDirectoryPath(fragment);
+ if (!ts.hasTrailingDirectorySeparator(fragment)) {
+ fragment = ts.getDirectoryPath(fragment);
+ }
if (fragment === "") {
fragment = "." + ts.directorySeparator;
}
fragment = ts.ensureTrailingDirectorySeparator(fragment);
- var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment));
- var baseDirectory = ts.getDirectoryPath(absolutePath);
+ // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
+ var absolutePath = ts.resolvePath(scriptPath, fragment);
+ var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
if (tryDirectoryExists(host, baseDirectory)) {
// Enumerate the available files if possible
@@ -85489,7 +87062,7 @@ var ts;
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
}
- var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
+ var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
if (!foundFiles.has(foundFileName)) {
foundFiles.set(foundFileName, true);
}
@@ -85502,8 +87075,8 @@ var ts;
var directories = tryGetDirectories(host, baseDirectory);
if (directories) {
for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) {
- var directory = directories_1[_a];
- var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
+ var directory_2 = directories_1[_a];
+ var directoryName = ts.getBaseFileName(ts.normalizePath(directory_2));
if (directoryName !== "@types") {
result.push(nameAndKind(directoryName, "directory" /* directory */));
}
@@ -85522,7 +87095,7 @@ var ts;
function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
var result = [];
- var fileExtensions = ts.getSupportedExtensions(compilerOptions);
+ var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (baseUrl) {
var projectDir = compilerOptions.project || host.getCurrentDirectory();
var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl);
@@ -85530,7 +87103,7 @@ var ts;
for (var path in paths) {
var patterns = paths[path];
if (paths.hasOwnProperty(path) && patterns) {
- var _loop_10 = function (name, kind) {
+ var _loop_12 = function (name, kind) {
// Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
if (!result.some(function (entry) { return entry.name === name; })) {
result.push(nameAndKind(name, kind));
@@ -85538,12 +87111,12 @@ var ts;
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind;
- _loop_10(name, kind);
+ _loop_12(name, kind);
}
}
}
}
- var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined;
+ var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) {
var ambientName = _d[_c];
result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */));
@@ -85554,7 +87127,7 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_11 = function (moduleName) {
+ var _loop_13 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */));
@@ -85562,7 +87135,7 @@ var ts;
};
for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) {
var moduleName = _f[_e];
- _loop_11(moduleName);
+ _loop_13(moduleName);
}
}
if (!foundGlobal) {
@@ -85598,12 +87171,13 @@ var ts;
}
// The prefix has two effective parts: the directory path and the base component after the filepath that is not a
// full directory component. For example: directory/path/of/prefix/base*
- var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix);
- var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix);
- var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix);
+ var normalizedPrefix = ts.resolvePath(parsed.prefix);
+ var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
+ var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
var fragmentHasPath = containsSlash(fragment);
+ var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
// Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
- var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory;
+ var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
var normalizedSuffix = ts.normalizePath(parsed.suffix);
// Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
@@ -85764,15 +87338,6 @@ var ts;
}
return false;
}
- function normalizeAndPreserveTrailingSlash(path) {
- if (ts.normalizeSlashes(path) === "./") {
- // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case.
- // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning.
- return "";
- }
- var norm = ts.normalizePath(path);
- return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm;
- }
/**
* Matches a triple slash reference directive with an incomplete string literal for its path. Used
* to determine if the caret is currently within the string literal and capture the literal fragment
@@ -85892,7 +87457,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
- var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); });
+ var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); });
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
}
default:
@@ -86459,11 +88024,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 277 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 293 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 297 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -86599,12 +88164,8 @@ var ts;
}
else if (isRightOfOpenTag) {
var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
- if (tryGetGlobalSymbols()) {
- symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); }));
- }
- else {
- symbols = tagSymbols;
- }
+ tryGetGlobalSymbols();
+ symbols = tagSymbols.concat(symbols);
completionKind = 3 /* MemberLike */;
}
else if (isStartingCloseTag) {
@@ -86628,11 +88189,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
- case 289 /* JSDocReturnTag */:
- case 290 /* JSDocTypeTag */:
- case 292 /* JSDocTypedefTag */:
+ case 292 /* JSDocParameterTag */:
+ case 297 /* JSDocPropertyTag */:
+ case 293 /* JSDocReturnTag */:
+ case 294 /* JSDocTypeTag */:
+ case 296 /* JSDocTypedefTag */:
return true;
}
}
@@ -86894,7 +88455,7 @@ var ts;
var exportedSymbols = typeChecker.getExportsOfModule(symbol);
// If the exported symbols contains type,
// symbol can be referenced at locations where type is allowed
- return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation);
+ return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation);
}
}
function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) {
@@ -87670,7 +89231,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 294 /* SyntaxList */:
+ case 298 /* 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);
@@ -87707,6 +89268,9 @@ var ts;
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
switch (triggerCharacter) {
+ case ".":
+ case "@":
+ return true;
case '"':
case "'":
case "`":
@@ -87715,8 +89279,12 @@ var ts;
case "<":
// Opening JSX tag
return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */;
+ case "/":
+ return ts.isStringLiteralLike(contextToken)
+ ? !!ts.tryGetImportFromModuleSpecifier(contextToken)
+ : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent);
default:
- return ts.Debug.fail(triggerCharacter);
+ return ts.Debug.assertNever(triggerCharacter);
}
}
function isStringLiteralOrTemplate(node) {
@@ -87811,6 +89379,10 @@ var ts;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]);
+ case 121 /* AwaitKeyword */:
+ return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
+ case 120 /* AsyncKeyword */:
+ return highlightSpans(getAsyncAndAwaitOccurrences(node));
default:
return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
? highlightSpans(getModifierOccurrences(node.kind, node.parent))
@@ -88058,6 +89630,29 @@ var ts;
});
return keywords;
}
+ function getAsyncAndAwaitOccurrences(node) {
+ var func = ts.getContainingFunction(node);
+ if (!func) {
+ return undefined;
+ }
+ var keywords = [];
+ if (func.modifiers) {
+ func.modifiers.forEach(function (modifier) {
+ pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */);
+ });
+ }
+ ts.forEachChild(func, aggregate);
+ return keywords;
+ function aggregate(node) {
+ if (ts.isAwaitExpression(node)) {
+ pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */);
+ }
+ // Do not cross function boundaries.
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
+ ts.forEachChild(node, aggregate);
+ }
+ }
+ }
function getIfElseOccurrences(ifStatement, sourceFile) {
var keywords = getIfElseKeywords(ifStatement, sourceFile);
var result = [];
@@ -88178,9 +89773,10 @@ var ts;
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
+ var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target;
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
- var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind);
+ var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
entry = {
sourceFile: sourceFile,
languageServiceRefCount: 1,
@@ -88309,6 +89905,8 @@ var ts;
addIndirectUser(direct.getSourceFile());
}
break;
+ case 71 /* Identifier */: // for 'const x = require("y");
+ break; // TODO: GH#23879
case 242 /* ImportEqualsDeclaration */:
handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */));
break;
@@ -88338,6 +89936,11 @@ var ts;
directImports.push(direct);
}
break;
+ case 178 /* ImportType */:
+ directImports.push(direct);
+ break;
+ default:
+ ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct));
}
}
}
@@ -88415,6 +90018,14 @@ var ts;
return;
}
if (decl.kind === 178 /* ImportType */) {
+ if (decl.qualifier) {
+ if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) {
+ singleReferences.push(decl.qualifier);
+ }
+ }
+ else if (exportKind === 2 /* ExportEquals */) {
+ singleReferences.push(decl.argument.literal);
+ }
return;
}
// Ignore if there's a grammar error
@@ -88442,7 +90053,7 @@ var ts;
var name = importClause.name;
// If a default import has the same name as the default export, allow to rename it.
// Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
- if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) {
+ if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
var defaultImportAlias = checker.getSymbolAtLocation(name);
addSearch(name, defaultImportAlias);
}
@@ -88500,24 +90111,18 @@ var ts;
function findNamespaceReExports(sourceFileLike, name, checker) {
var namespaceImportSymbol = checker.getSymbolAtLocation(name);
return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
- if (statement.kind !== 249 /* ExportDeclaration */)
+ if (!ts.isExportDeclaration(statement))
return;
- var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier;
- if (moduleSpecifier || !exportClause)
- return;
- for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) {
- var element = _b[_i];
- if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) {
- return true;
- }
- }
+ var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
+ return !moduleSpecifier && exportClause &&
+ exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
});
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var referencingFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var referencingFile = sourceFiles_5[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === 273 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
@@ -88547,8 +90152,8 @@ var ts;
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
var map = ts.createMap();
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
@@ -88653,6 +90258,9 @@ var ts;
else if (ts.isBinaryExpression(parent.parent)) {
return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true);
}
+ else if (ts.isJSDocTypedefTag(parent)) {
+ return exportInfo(symbol, 0 /* Named */);
+ }
}
function getExportAssignmentExport(ex) {
// Get the symbol for the `export =` node; its parent is the module it's the export of.
@@ -88697,7 +90305,7 @@ var ts;
// If the import has a different name than the export, do not continue searching.
// If `importedName` is undefined, do continue searching as the export is anonymous.
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
- var importedName = symbolName(importedSymbol);
+ var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
}
@@ -88764,15 +90372,6 @@ var ts;
return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
}
FindAllReferences.getExportInfo = getExportInfo;
- function symbolName(symbol) {
- if (symbol.escapedName !== "default" /* Default */) {
- return symbol.escapedName;
- }
- return ts.forEach(symbol.declarations, function (decl) {
- var name = ts.getNameOfDeclaration(decl);
- return name && name.kind === 71 /* Identifier */ && name.escapedText;
- });
- }
/** If at an export specifier, go to the symbol it refers to. */
function skipExportSpecifierSymbol(symbol, checker) {
// For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
@@ -88847,9 +90446,9 @@ var ts;
// 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 === 270 /* ShorthandPropertyAssignment */) {
- var result_4 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); });
- return result_4;
+ var result_5 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); });
+ return result_5;
}
else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -88882,8 +90481,8 @@ var ts;
case "symbol": {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ var name_3 = displayParts_1.map(function (p) { return p.text; }).join("");
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 };
}
case "label": {
var node_3 = def.node;
@@ -88891,13 +90490,13 @@ var ts;
}
case "keyword": {
var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var name_4 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] };
}
case "this": {
var node_5 = def.node;
var symbol = checker.getSymbolAtLocation(node_5);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case "string": {
@@ -89010,7 +90609,7 @@ var ts;
if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
if (ts.isSourceFile(node)) {
var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
- return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet);
+ return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
}
if (!options.implementations) {
var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
@@ -89025,32 +90624,36 @@ var ts;
// String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
}
- if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) {
- return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet);
+ var moduleReferences = ts.emptyArray;
+ var moduleSourceFile = isModuleSymbol(symbol);
+ if (moduleSourceFile) {
+ var exportEquals = symbol.exports.get("export=" /* ExportEquals */);
+ // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
+ moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
+ if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
+ return moduleReferences;
+ // Continue to get references to 'export ='.
+ symbol = ts.skipAlias(exportEquals, checker);
+ node = undefined;
}
- return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
+ return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
}
Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
- function isModuleReferenceLocation(node) {
- if (!ts.isStringLiteralLike(node)) {
- return false;
- }
- switch (node.parent.kind) {
- case 238 /* ModuleDeclaration */:
- case 253 /* ExternalModuleReference */:
- case 243 /* ImportDeclaration */:
- case 249 /* ExportDeclaration */:
- return true;
- case 186 /* CallExpression */:
- return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent);
- default:
- return false;
- }
+ function isModuleSymbol(symbol) {
+ return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile);
}
- function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) {
+ function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
ts.Debug.assert(!!symbol.valueDeclaration);
- var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) {
+ var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) {
if (reference.kind === "import") {
+ var parent = reference.literal.parent;
+ if (ts.isLiteralTypeNode(parent)) {
+ var importType = ts.cast(parent.parent, ts.isImportTypeNode);
+ if (excludeImportTypeOfExportEquals && !importType.qualifier) {
+ return undefined;
+ }
+ }
+ // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway.
return { type: "node", node: reference.literal };
}
else {
@@ -89073,10 +90676,11 @@ var ts;
}
break;
default:
+ // This may be merged with something.
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return [{ definition: { type: "symbol", symbol: symbol }, references: references }];
+ return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray;
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
@@ -89104,17 +90708,17 @@ var ts;
}
/** Core find-all-references algorithm for a normal symbol. */
function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
- symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
+ symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
// Compute the meaning from the location and the symbol it references
- var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
+ var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
var result = [];
- var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
- if (node.kind === 79 /* DefaultKeyword */) {
+ var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
+ if (node && node.kind === 79 /* DefaultKeyword */) {
addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
else {
- var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) });
+ var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] });
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
@@ -89160,7 +90764,6 @@ var ts;
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
- ts.Debug.assert(decl.kind === 273 /* SourceFile */);
ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol));
}
return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
@@ -89234,7 +90837,7 @@ var ts;
// here appears to be intentional).
var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b;
var escapedText = ts.escapeLeadingUnderscores(text);
- var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
+ var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } };
};
/**
@@ -89278,10 +90881,8 @@ var ts;
var addRef = state.referenceAdder(exportSymbol);
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
- // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
+ if (shouldAddSingleReference(singleRef, state))
addRef(singleRef);
- }
}
}
// For each import, find all references to that import in its source file.
@@ -89310,6 +90911,17 @@ var ts;
}
}
}
+ function shouldAddSingleReference(singleRef, state) {
+ if (!hasMatchingMeaning(singleRef, state))
+ return false;
+ if (!state.options.isForRename)
+ return true;
+ // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;`
+ if (!ts.isIdentifier(singleRef))
+ return false;
+ // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
+ return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
+ }
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol, state) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -89333,22 +90945,14 @@ var ts;
var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */);
if (bindingElement &&
bindingElement.parent.kind === 179 /* ObjectBindingPattern */ &&
+ ts.isIdentifier(bindingElement.name) &&
!bindingElement.propertyName) {
return bindingElement;
}
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
var bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
- if (!bindingElement)
- return undefined;
- var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
- var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
- if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
- // See GH#16922
- ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
- return propSymbol.target;
- }
- return propSymbol;
+ return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement);
}
/**
* Determines the smallest scope in which a symbol may have named references.
@@ -89519,6 +91123,9 @@ var ts;
getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
}
}
+ function hasMatchingMeaning(referenceLocation, state) {
+ return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
+ }
function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
@@ -89534,9 +91141,8 @@ var ts;
}
return;
}
- if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
+ if (!hasMatchingMeaning(referenceLocation, state))
return;
- }
var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
if (!referenceSymbol) {
return;
@@ -90197,7 +91803,9 @@ var ts;
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.
- return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; })
+ return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) ||
+ // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias
+ symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })
? [sigInfo]
: [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node));
}
@@ -90252,14 +91860,14 @@ var ts;
function getReferenceAtPosition(sourceFile, position, program) {
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
if (referencePath) {
- var file = ts.tryResolveScriptReference(program, sourceFile, referencePath);
- return file && { fileName: referencePath.fileName, file: file };
+ var file_16 = ts.tryResolveScriptReference(program, sourceFile, referencePath);
+ return file_16 && { fileName: referencePath.fileName, file: file_16 };
}
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
- var file = reference && program.getSourceFile(reference.resolvedFileName);
- return file && { fileName: typeReferenceDirective.fileName, file: file };
+ var file_17 = reference && program.getSourceFile(reference.resolvedFileName);
+ return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 };
}
return undefined;
}
@@ -90431,6 +92039,7 @@ var ts;
"author",
"argument",
"borrows",
+ "callback",
"class",
"constant",
"constructor",
@@ -90495,10 +92104,12 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 293 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
+ case 297 /* JSDocPropertyTag */:
return [declaration];
- case 292 /* JSDocTypedefTag */:
- return [declaration.parent];
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
}
@@ -90518,15 +92129,16 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 286 /* JSDocAugmentsTag */:
+ case 289 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 290 /* JSDocTypeTag */:
+ case 294 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 292 /* JSDocTypedefTag */:
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ case 297 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -90851,12 +92463,42 @@ var ts;
JsTyping.isTypingUpToDate = isTypingUpToDate;
/* @internal */
JsTyping.nodeCoreModuleList = [
- "buffer", "querystring", "events", "http", "cluster",
- "zlib", "os", "https", "punycode", "repl", "readline",
- "vm", "child_process", "url", "dns", "net",
- "dgram", "fs", "path", "string_decoder", "tls",
- "crypto", "stream", "util", "assert", "tty", "domain",
- "constants", "process", "v8", "timers", "console"
+ "assert",
+ "async_hooks",
+ "buffer",
+ "child_process",
+ "cluster",
+ "console",
+ "constants",
+ "crypto",
+ "dgram",
+ "dns",
+ "domain",
+ "events",
+ "fs",
+ "http",
+ "https",
+ "http2",
+ "inspector",
+ "net",
+ "os",
+ "path",
+ "perf_hooks",
+ "process",
+ "punycode",
+ "querystring",
+ "readline",
+ "repl",
+ "stream",
+ "string_decoder",
+ "timers",
+ "tls",
+ "tty",
+ "url",
+ "util",
+ "v8",
+ "vm",
+ "zlib"
];
/* @internal */
JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
@@ -90915,8 +92557,8 @@ var ts;
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
- var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
- addInferredTypings(module, "Inferred typings from unresolved imports");
+ var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ addInferredTypings(module_1, "Inferred typings from unresolved imports");
}
// Add the cached typing locations for inferred typings that are already installed
packageNameToTypingLocation.forEach(function (typing, name) {
@@ -91013,8 +92655,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_5.config;
+ var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_6.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
@@ -91114,7 +92756,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_12 = function (sourceFile) {
+ var _loop_14 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) {
return "continue";
@@ -91124,9 +92766,9 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_12(sourceFile);
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var sourceFile = sourceFiles_7[_i];
+ _loop_14(sourceFile);
}
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
@@ -91503,7 +93145,7 @@ var ts;
if (ts.hasJSDocNodes(node)) {
ts.forEach(node.jsDoc, function (jsDoc) {
ts.forEach(jsDoc.tags, function (tag) {
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (ts.isJSDocTypeAlias(tag)) {
addLeafNode(tag);
}
});
@@ -91578,6 +93220,7 @@ var ts;
}
/** Merge source into target. Source should be thrown away after this is called. */
function merge(target, source) {
+ var _a;
target.additionalNodes = target.additionalNodes || [];
target.additionalNodes.push(source.node);
if (source.additionalNodes) {
@@ -91588,7 +93231,6 @@ var ts;
mergeChildren(target.children);
sortChildren(target.children);
}
- var _a;
}
/** Recursively ensure that each NavNode's children are in sorted order. */
function sortChildren(children) {
@@ -91616,8 +93258,6 @@ var ts;
case 192 /* ArrowFunction */:
case 204 /* ClassExpression */:
return getFunctionOrClassName(node);
- case 292 /* JSDocTypedefTag */:
- return getJSDocTypedefTagName(node);
default:
return undefined;
}
@@ -91659,29 +93299,10 @@ var ts;
return "()";
case 159 /* IndexSignature */:
return "[]";
- case 292 /* JSDocTypedefTag */:
- return getJSDocTypedefTagName(node);
default:
return "";
}
}
- function getJSDocTypedefTagName(node) {
- if (node.name) {
- return node.name.text;
- }
- else {
- var parentNode = node.parent && node.parent.parent;
- if (parentNode && parentNode.kind === 213 /* VariableStatement */) {
- if (parentNode.declarationList.declarations.length > 0) {
- var nameIdentifier = parentNode.declarationList.declarations[0].name;
- if (nameIdentifier.kind === 71 /* Identifier */) {
- return nameIdentifier.text;
- }
- }
- }
- return "";
- }
- }
/** Flattens the NavNode tree to a list, keeping only the top-level items. */
function topLevelItems(root) {
var topLevel = [];
@@ -91707,7 +93328,8 @@ var ts;
case 238 /* ModuleDeclaration */:
case 273 /* SourceFile */:
case 236 /* TypeAliasDeclaration */:
- case 292 /* JSDocTypedefTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
return true;
case 154 /* Constructor */:
case 153 /* MethodDeclaration */:
@@ -91870,17 +93492,23 @@ var ts;
*/
function organizeImports(sourceFile, formatContext, host, program, _preferences) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
+ var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
// All of the old ImportDeclarations in the file, in syntactic order.
var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
- organizeImportsWorker(topLevelImportDecls);
+ organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
+ // All of the old ExportDeclarations in the file, in syntactic order.
+ var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
+ organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
var ambientModule = _a[_i];
var ambientModuleBody = getModuleBlock(ambientModule);
var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
- organizeImportsWorker(ambientModuleImportDecls);
+ organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
+ var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
+ organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
- function organizeImportsWorker(oldImportDecls) {
+ function organizeImportsWorker(oldImportDecls, coalesce) {
if (ts.length(oldImportDecls) === 0) {
return;
}
@@ -91894,7 +93522,7 @@ var ts;
var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
return getExternalModuleName(importGroup[0].moduleSpecifier)
- ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
+ ? coalesce(importGroup)
: importGroup;
});
// Delete or replace the first import.
@@ -91969,7 +93597,9 @@ var ts;
}
}
function getExternalModuleName(specifier) {
- return ts.isStringLiteralLike(specifier) ? specifier.text : undefined;
+ return specifier !== undefined && ts.isStringLiteralLike(specifier)
+ ? specifier.text
+ : undefined;
}
/* @internal */ // Internal for testing
/**
@@ -92015,15 +93645,14 @@ var ts;
}
}
newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
- var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
- return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
- compareIdentifiers(s1.name, s2.name);
- });
+ var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
var importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
var newNamedImports = sortedImportSpecifiers.length === 0
- ? undefined
+ ? newDefaultImport
+ ? undefined
+ : ts.createNamedImports(ts.emptyArray)
: namedImports.length === 0
? ts.createNamedImports(sortedImportSpecifiers)
: ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers);
@@ -92069,23 +93698,77 @@ var ts;
namedImports: namedImports,
};
}
- function compareIdentifiers(s1, s2) {
- return ts.compareStringsCaseSensitive(s1.text, s2.text);
- }
}
OrganizeImports.coalesceImports = coalesceImports;
+ /* @internal */ // Internal for testing
+ /**
+ * @param exportGroup a list of ExportDeclarations, all with the same module name.
+ */
+ function coalesceExports(exportGroup) {
+ if (exportGroup.length === 0) {
+ return exportGroup;
+ }
+ var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
+ var coalescedExports = [];
+ if (exportWithoutClause) {
+ coalescedExports.push(exportWithoutClause);
+ }
+ if (namedExports.length === 0) {
+ return coalescedExports;
+ }
+ var newExportSpecifiers = [];
+ newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
+ var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
+ var exportDecl = namedExports[0];
+ coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
+ return coalescedExports;
+ /*
+ * Returns entire export declarations because they may already have been rewritten and
+ * may lack parent pointers. The desired parts can easily be recovered based on the
+ * categorization.
+ */
+ function getCategorizedExports(exportGroup) {
+ var exportWithoutClause;
+ var namedExports = [];
+ for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
+ var exportDeclaration = exportGroup_1[_i];
+ if (exportDeclaration.exportClause === undefined) {
+ // Only the first such export is interesting - the others are redundant.
+ // Note: Unfortunately, we will lose trivia that was on this node.
+ exportWithoutClause = exportWithoutClause || exportDeclaration;
+ }
+ else {
+ namedExports.push(exportDeclaration);
+ }
+ }
+ return {
+ exportWithoutClause: exportWithoutClause,
+ namedExports: namedExports,
+ };
+ }
+ }
+ OrganizeImports.coalesceExports = coalesceExports;
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
}
+ function sortSpecifiers(specifiers) {
+ return ts.stableSort(specifiers, function (s1, s2) {
+ return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
+ compareIdentifiers(s1.name, s2.name);
+ });
+ }
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
var name2 = getExternalModuleName(m2);
return ts.compareBooleans(name1 === undefined, name2 === undefined) ||
ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) ||
- ts.compareStringsCaseSensitive(name1, name2);
+ ts.compareStringsCaseInsensitive(name1, name2);
}
OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
+ function compareIdentifiers(s1, s2) {
+ return ts.compareStringsCaseInsensitive(s1.text, s2.text);
+ }
})(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
})(ts || (ts = {}));
/* @internal */
@@ -92095,7 +93778,7 @@ var ts;
var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
- for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate;
var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
@@ -92107,25 +93790,16 @@ var ts;
}
ts.getEditsForFileRename = getEditsForFileRename;
function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) {
- var cfg = program.getCompilerOptions().configFile;
- if (!cfg)
- return;
- var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath);
+ var configFile = program.getCompilerOptions().configFile;
+ var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath);
if (oldFile) {
- changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath);
+ changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath);
}
}
- function getFilesEntry(cfg, fileName) {
- var filesProp = ts.find(cfg.properties, function (prop) {
- return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
- });
- var files = filesProp && filesProp.initializer;
- return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined;
- }
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
- function getImportsToUpdate(program, oldFilePath) {
+ function getImportsToUpdate(program, oldFilePath, host) {
var checker = program.getTypeChecker();
var result = [];
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
@@ -92141,8 +93815,10 @@ var ts;
// If it resolved to something already, ignore.
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
- var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
- if (ts.contains(resolved.failedLookupLocations, oldFilePath)) {
+ var resolved = host.resolveModuleNames
+ ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
+ : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
+ if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
}
@@ -92151,11 +93827,11 @@ var ts;
}
function getPathUpdater(oldFilePath, newFilePath, host) {
// Get the relative path from old to new location, and append it on to the end of imports and normalize.
- var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
+ var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
return function (oldPath) {
if (!ts.pathIsRelative(oldPath))
return;
- return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
+ return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
};
}
function createStringRange(node, sourceFile) {
@@ -92176,7 +93852,27 @@ var ts;
OutliningElementsCollector.collectElements = collectElements;
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
var depthRemaining = 40;
- sourceFile.forEachChild(function walk(n) {
+ var current = 0;
+ var statements = sourceFile.statements;
+ var n = statements.length;
+ while (current < n) {
+ while (current < n && !ts.isAnyImportSyntax(statements[current])) {
+ visitNonImportNode(statements[current]);
+ current++;
+ }
+ if (current === n)
+ break;
+ var firstImport = current;
+ while (current < n && ts.isAnyImportSyntax(statements[current])) {
+ addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
+ current++;
+ }
+ var lastImport = current - 1;
+ if (lastImport !== firstImport) {
+ out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
+ }
+ }
+ function visitNonImportNode(n) {
if (depthRemaining === 0)
return;
cancellationToken.throwIfCancellationRequested();
@@ -92189,17 +93885,17 @@ var ts;
depthRemaining--;
if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
// Consider an 'else if' to be on the same depth as the 'if'.
- walk(n.expression);
- walk(n.thenStatement);
+ visitNonImportNode(n.expression);
+ visitNonImportNode(n.thenStatement);
depthRemaining++;
- walk(n.elseStatement);
+ visitNonImportNode(n.elseStatement);
depthRemaining--;
}
else {
- n.forEachChild(walk);
+ n.forEachChild(visitNonImportNode);
}
depthRemaining++;
- });
+ }
}
function addRegionOutliningSpans(sourceFile, out) {
var regions = [];
@@ -92214,7 +93910,7 @@ var ts;
}
if (!result[1]) {
var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region"));
+ regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -92248,7 +93944,7 @@ var ts;
break;
case 3 /* MultiLineCommentTrivia */:
combineAndAddMultipleSingleLineComments();
- out.push(createOutliningSpanFromBounds(pos, end));
+ out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
singleLineCommentCount = 0;
break;
default:
@@ -92259,12 +93955,12 @@ var ts;
function combineAndAddMultipleSingleLineComments() {
// Only outline spans of two or more consecutive single line comments
if (singleLineCommentCount > 1) {
- out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd));
+ out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
}
}
}
- function createOutliningSpanFromBounds(pos, end) {
- return createOutliningSpan(ts.createTextSpanFromBounds(pos, end));
+ function createOutliningSpanFromBounds(pos, end, kind) {
+ return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
switch (n.kind) {
@@ -92298,7 +93994,7 @@ var ts;
default:
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
- return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile));
+ return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
}
case 239 /* ModuleBlock */:
return spanForNode(n.parent);
@@ -92330,14 +94026,14 @@ var ts;
return undefined;
}
var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
- return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
+ return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
}
- function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) {
+ function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
if (hintSpan === void 0) { hintSpan = textSpan; }
if (autoCollapse === void 0) { autoCollapse = false; }
if (bannerText === void 0) { bannerText = "..."; }
- return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
+ return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
}
})(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
})(ts || (ts = {}));
@@ -92620,13 +94316,13 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_13 = function (start) {
+ var _loop_15 = function (start) {
if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
return { value: start };
}
};
for (var start = 0; start <= n; start++) {
- var state_4 = _loop_13(start);
+ var state_4 = _loop_15(start);
if (typeof state_4 === "object")
return state_4.value;
}
@@ -93172,6 +94868,9 @@ var ts;
if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
return undefined;
}
+ // Can't rename a module name.
+ if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node))
+ return undefined;
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
@@ -93291,7 +94990,7 @@ var ts;
var nameToDeclarations = sourceFile.getNamedDeclarations();
var declarations = nameToDeclarations.get(name.text);
if (declarations) {
- var _loop_14 = function (declaration) {
+ var _loop_16 = function (declaration) {
var symbol = declaration.symbol;
if (symbol) {
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
@@ -93305,7 +95004,7 @@ var ts;
};
for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) {
var declaration = declarations_12[_b];
- var state_5 = _loop_14(declaration);
+ var state_5 = _loop_16(declaration);
if (typeof state_5 === "object")
return state_5.value;
}
@@ -93652,7 +95351,9 @@ var ts;
program.getSemanticDiagnostics(sourceFile);
var checker = program.getDiagnosticsProducingTypeChecker();
var diags = [];
- if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))) {
+ if (sourceFile.commonJsModuleIndicator &&
+ (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
+ containsTopLevelCommonjs(sourceFile)) {
diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
}
var isJsFile = ts.isSourceFileJavaScript(sourceFile);
@@ -93694,16 +95395,39 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
}
}
- return diags.concat(checker.getSuggestionDiagnostics(sourceFile));
+ return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; });
}
ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
+ // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
+ function containsTopLevelCommonjs(sourceFile) {
+ return sourceFile.statements.some(function (statement) {
+ switch (statement.kind) {
+ case 213 /* VariableStatement */:
+ return statement.declarationList.declarations.some(function (decl) {
+ return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
+ });
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ if (!ts.isBinaryExpression(expression))
+ return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
+ var kind = ts.getSpecialPropertyAssignmentKind(expression);
+ return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
+ }
+ default:
+ return false;
+ }
+ });
+ }
+ function propertyAccessLeftHandSide(node) {
+ return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
+ }
function importNameForConvertToDefaultImport(node) {
switch (node.kind) {
case 243 /* ImportDeclaration */:
@@ -94434,7 +96158,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_15 = function (opt) {
+ var _loop_17 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -94453,7 +96177,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_15(opt);
+ _loop_17(opt);
}
return options;
}
@@ -94857,6 +96581,7 @@ var ts;
rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
+ rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */),
// Special handling of unary operators.
// Prefix operators generally shouldn't have a space between
// them and their target unary expression.
@@ -95317,6 +97042,9 @@ var ts;
function isArrowFunctionContext(context) {
return context.contextNode.kind === 192 /* ArrowFunction */;
}
+ function isImportTypeContext(context) {
+ return context.contextNode.kind === 178 /* ImportType */;
+ }
function isNonJsxSameLineTokenContext(context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}
@@ -95439,18 +97167,18 @@ var ts;
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(map.length);
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
- var rule = rules_1[_i];
- var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
- for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
+ var rule_1 = rules_1[_i];
+ var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific;
+ for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) {
var left = _b[_a];
- for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) {
var right = _d[_c];
var index = getRuleBucketIndex(left, right);
var rulesBucket = map[index];
if (rulesBucket === undefined) {
rulesBucket = map[index] = [];
}
- addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
+ addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index);
}
}
}
@@ -96757,7 +98485,7 @@ var ts;
NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
})(NextTokenKind || (NextTokenKind = {}));
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
- var nextToken = ts.findNextToken(precedingToken, current);
+ var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
if (!nextToken) {
return 0 /* Unknown */;
}
@@ -96806,9 +98534,10 @@ var ts;
}
function getContainingList(node, sourceFile) {
if (node.parent) {
+ var end = node.end;
switch (node.parent.kind) {
case 161 /* TypeReference */:
- return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
case 183 /* ObjectLiteralExpression */:
return node.parent.properties;
case 182 /* ArrayLiteralExpression */:
@@ -96823,22 +98552,25 @@ var ts;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.parameters, start, end);
}
case 234 /* ClassDeclaration */:
- return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end);
case 187 /* NewExpression */:
case 186 /* CallExpression */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.arguments, start, end);
}
case 232 /* VariableDeclarationList */:
- return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
case 246 /* NamedImports */:
case 250 /* NamedExports */:
- return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
}
}
return undefined;
@@ -97160,10 +98892,10 @@ var ts;
return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getAdjustedEndPosition(sourceFile, node, options) {
+ var end = node.end;
if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
- return node.getEnd();
+ return end;
}
- var end = node.getEnd();
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
? newEnd
@@ -97188,7 +98920,8 @@ var ts;
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
this.changes = [];
- this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
+ 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
}
ChangeTracker.fromContext = function (context) {
@@ -97232,35 +98965,14 @@ var ts;
this.deleteNode(sourceFile, node);
return this;
}
- var id = ts.getNodeId(node);
- ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice");
- this.deletedNodesInLists[id] = true;
- if (index !== containingList.length - 1) {
- var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false);
- if (nextToken && isSeparator(node, nextToken)) {
- // find first non-whitespace position in the leading trivia of the node
- var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- var nextElement = containingList[index + 1];
- /// find first non-whitespace position in the leading trivia of the next node
- var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node
- this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- }
- }
- else {
- var prev = containingList[index - 1];
- if (this.deletedNodesInLists[ts.getNodeId(prev)]) {
- var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- var end = getAdjustedEndPosition(sourceFile, node, {});
- this.deleteRange(sourceFile, { pos: pos, end: end });
- }
- else {
- var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false);
- if (previousToken && isSeparator(node, previousToken)) {
- this.deleteNodeRange(sourceFile, previousToken, node);
- }
- }
- }
+ // 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) {
@@ -97289,10 +99001,13 @@ var ts;
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
+ ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
+ var next = ts.findNextToken(node, node.parent, sourceFile);
+ return next && next.kind === 26 /* CommaToken */ ? next : undefined;
+ };
ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
- return this.replaceNode(sourceFile, oldNode, newNode, {
- suffix: "," + this.newLineCharacter
- });
+ var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
+ return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
@@ -97326,7 +99041,8 @@ var ts;
// 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 text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter;
+ var indent = sourceFile.text.slice(lineStartPosition, startPosition);
+ var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
this.insertText(sourceFile, token.getStart(sourceFile), text);
};
ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
@@ -97399,20 +99115,38 @@ var ts;
};
ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
var clsStart = cls.getStart(sourceFile);
- var prefix = "";
- var suffix = this.newLineCharacter;
- if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
- prefix = this.newLineCharacter;
- // For `class C {\n}`, don't add the trailing "\n"
- if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any'
- suffix = "";
- }
- }
var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
+ this.formatContext.options.indentSize;
- this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix });
+ this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls)));
+ };
+ ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) {
+ if (cls.members.length === 0) {
+ if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
+ // For `class C {\n}`, don't add the trailing "\n"
+ var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any'
+ return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" };
+ }
+ else {
+ return { prefix: "", suffix: this.newLineCharacter };
+ }
+ }
+ else {
+ return { prefix: this.newLineCharacter, suffix: "" };
+ }
+ };
+ ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
};
ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ 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));
+ };
+ ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
if (needSemicolonBetween(after, newNode)) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
@@ -97421,9 +99155,13 @@ var ts;
}
}
var endPosition = getAdjustedEndPosition(sourceFile, after, {});
- return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after));
+ return endPosition;
};
- ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) {
+ ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
+ var options = this.getInsertNodeAfterOptionsWorker(after);
+ 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 };
}
@@ -97468,13 +99206,16 @@ var ts;
this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
}
};
+ ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
+ this.insertText(sourceFile, node.getStart(sourceFile), "export ");
+ };
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
* i.e. arguments in arguments lists, parameters in parameter lists etc.
* Note that separators are part of the node in statements and class elements.
*/
- ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
- var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
+ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
+ if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
return this;
@@ -97592,6 +99333,19 @@ var ts;
}
});
};
+ ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () {
+ var _this = this;
+ this.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);
+ if (lastNonDeletedIndex !== -1) {
+ _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
+ }
+ });
+ };
/**
* Note: after calling this, the TextChanges object must be discarded!
* @param validate only for tests
@@ -97600,11 +99354,24 @@ var ts;
*/
ChangeTracker.prototype.getChanges = function (validate) {
this.finishClassesWithNodesInsertedAtStart();
- return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ 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;
+ changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter));
+ }
+ return changes;
+ };
+ ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
+ this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
};
return ChangeTracker;
}());
textChanges_3.ChangeTracker = ChangeTracker;
+ // find first non-whitespace position in the leading trivia of the node
+ function startPositionToDeleteNodeInList(sourceFile, node) {
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ }
function getClassBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end];
}
@@ -97614,15 +99381,16 @@ var ts;
return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
var sourceFile = changesInFile[0].sourceFile;
// order changes by start position
- var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
- var _loop_16 = function (i) {
+ // 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_18 = 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_16(i);
+ _loop_18(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -97631,6 +99399,11 @@ var ts;
});
}
changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function newFileChanges(oldFile, fileName, statements, newLineCharacter) {
+ var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
+ return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true };
+ }
+ changesToText.newFileChanges = newFileChanges;
function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
if (change.kind === ChangeKind.Remove) {
return "";
@@ -97980,10 +99753,11 @@ var ts;
}
refactor_1.getEditsForRefactor = getEditsForRefactor;
})(refactor = ts.refactor || (ts.refactor = {}));
- function getRefactorContextLength(context) {
- return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition;
+ function getRefactorContextSpan(_a) {
+ var startPosition = _a.startPosition, endPosition = _a.endPosition;
+ return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
}
- ts.getRefactorContextLength = getRefactorContextLength;
+ ts.getRefactorContextSpan = getRefactorContextSpan;
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -98051,7 +99825,7 @@ var ts;
if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
if (!decl.typeParameters) {
var typeParameters = ts.getJSDocTypeParameterDeclarations(decl);
- if (typeParameters)
+ if (typeParameters.length)
changes.insertTypeParameters(sourceFile, decl, typeParameters);
}
var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile);
@@ -98087,18 +99861,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 161 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -98122,7 +99896,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
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);
@@ -98403,7 +100177,7 @@ var ts;
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
switch (importNode.kind) {
case 242 /* ImportEqualsDeclaration */:
- changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
+ changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
break;
case 186 /* CallExpression */:
if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
@@ -98467,7 +100241,7 @@ var ts;
case 186 /* CallExpression */: {
if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
// For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
+ changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
}
return false;
}
@@ -98540,27 +100314,30 @@ var ts;
changes.deleteNode(sourceFile, assignment.parent);
}
else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
+ : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
+ : undefined;
+ if (replacement) {
+ changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
+ return replacement[1];
+ }
+ else {
+ changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default");
+ return true;
}
- changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
- return changedToDefaultExport;
}
}
else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
convertNamedExport(sourceFile, assignment, changes, exports);
}
return false;
- var _a;
}
/**
* Convert `module.exports = { ... }` to individual exports..
* We can't always do this if the module has interesting members -- then it will be a default export instead.
*/
function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
+ var statements = ts.mapAllOrFail(object.properties, function (prop) {
switch (prop.kind) {
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
@@ -98576,6 +100353,7 @@ var ts;
ts.Debug.assertNever(prop);
}
});
+ return statements && [statements, false];
}
function convertNamedExport(sourceFile, assignment, changes, exports) {
// If "originalKeywordKind" was set, this is e.g. `exports.
@@ -98596,30 +100374,6 @@ var ts;
convertExportsPropertyAssignment(assignment, sourceFile, changes);
}
}
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 191 /* FunctionExpression */:
- case 192 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 204 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 186 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
function convertReExportAll(reExported, checker) {
// `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
var moduleSpecifier = reExported.text;
@@ -98695,7 +100449,7 @@ var ts;
: makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
});
if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
}
}
// falls through -- object destructuring has an interesting pattern and must be a variable declaration
@@ -98706,7 +100460,7 @@ var ts;
*/
var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
];
}
@@ -98755,7 +100509,7 @@ var ts;
// If it was unused, ensure that we at least import *something*.
needDefaultImport = true;
}
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
}
// Identifiers helpers
function makeUniqueName(name, identifiers) {
@@ -98797,17 +100551,9 @@ var ts;
}
function makeSingleImport(localName, propertyName, moduleSpecifier) {
return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
}
- function makeImport(name, namedImports, moduleSpecifier) {
- return makeImportDeclaration(name, namedImports, moduleSpecifier);
- }
- function makeImportDeclaration(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
- }
- codefix.makeImportDeclaration = makeImportDeclaration;
function makeImportSpecifier(propertyName, name) {
return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
}
@@ -98968,7 +100714,7 @@ var ts;
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, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier;
+ 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)) };
}
@@ -99014,11 +100760,11 @@ var ts;
if (context.symbolToken && ts.isIdentifier(context.symbolToken)) {
for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) {
var declaration = existingImports_1[_i].declaration;
- var namespace = getNamespaceImportName(declaration);
- if (namespace) {
- var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace));
+ var namespace_2 = getNamespaceImportName(declaration);
+ if (namespace_2) {
+ var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2));
if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) {
- useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken));
+ useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken));
}
}
}
@@ -99085,12 +100831,6 @@ var ts;
return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile);
}
}
- function usesJsExtensionOnImports(sourceFile) {
- return ts.firstDefined(sourceFile.imports, function (_a) {
- var text = _a.text;
- return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined;
- }) || false;
- }
function createImportClauseOfKind(kind, symbolName) {
var id = ts.createIdentifier(symbolName);
switch (kind) {
@@ -99104,274 +100844,15 @@ var ts;
ts.Debug.assertNever(kind);
}
}
- function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) {
- var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
- var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
- var addJsExtension = usesJsExtensionOnImports(sourceFile);
+ function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) {
var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind;
- var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) {
- var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName);
- var global = tryGetModuleNameFromAmbientModule(moduleSymbol)
- || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension)
- || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory)
- || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName);
- if (global) {
- return [global];
- }
- var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension);
- if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
- return [relativePath];
- }
- var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
- if (!relativeToBaseUrl) {
- return [relativePath];
- }
- var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension);
- if (paths) {
- var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
- if (fromPaths) {
- return [fromPaths];
- }
- }
- if (preferences.importModuleSpecifierPreference === "non-relative") {
- return [importRelativeToBaseUrl];
- }
- if (preferences.importModuleSpecifierPreference !== undefined)
- ts.Debug.assertNever(preferences.importModuleSpecifierPreference);
- if (isPathRelativeToParent(relativeToBaseUrl)) {
- return [relativePath];
- }
- /*
- Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl.
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/a/b
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../../foo/bar
- getRelativePathNParents(relativePath) = 2
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 2 < 2 = false
- In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar".
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/foo/a
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../a
- getRelativePathNParents(relativePath) = 1
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 1 < 2 = true
- In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
- */
- var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName);
- var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
- return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
- });
+ var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences);
return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ 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; }));
}
- /**
- * Looks for a existing imports that use symlinks to this module.
- * Only if no symlink is available, the real path will be used.
- */
- function getAllModulePaths(program, _a) {
- var fileName = _a.fileName;
- var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) {
- return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
- return res && res.resolvedFileName === fileName ? res.originalPath : undefined;
- });
- });
- return symlinks.length === 0 ? [fileName] : symlinks;
- }
- function getRelativePathNParents(relativePath) {
- var count = 0;
- for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) {
- count++;
- }
- return count;
- }
- function tryGetModuleNameFromAmbientModule(moduleSymbol) {
- var decl = moduleSymbol.valueDeclaration;
- if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) {
- return decl.name.text;
- }
- }
- function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
- for (var key in paths) {
- for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
- var patternText_1 = _a[_i];
- var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
- var indexOfStar = pattern.indexOf("*");
- if (indexOfStar === 0 && pattern.length === 1) {
- continue;
- }
- else if (indexOfStar !== -1) {
- var prefix = pattern.substr(0, indexOfStar);
- var suffix = pattern.substr(indexOfStar + 1);
- if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
- ts.startsWith(relativeToBaseUrl, prefix) &&
- ts.endsWith(relativeToBaseUrl, suffix)) {
- var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
- return key.replace("*", matchedStar);
- }
- }
- else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
- return key;
- }
- }
- }
- }
- function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
- var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
- if (normalizedTargetPath === undefined) {
- return undefined;
- }
- var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
- var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath;
- return ts.removeFileExtension(relativePath);
- }
- function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
- var roots = ts.getEffectiveTypeRoots(options, host);
- return ts.firstDefined(roots, function (unNormalizedTypeRoot) {
- var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName);
- if (ts.startsWith(moduleFileName, typeRoot)) {
- // For a type definition, we can strip `/index` even with classic resolution.
- return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension);
- }
- });
- }
- function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) {
- if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
- // nothing to do here
- return undefined;
- }
- var parts = getNodeModulePathParts(moduleFileName);
- if (!parts) {
- return undefined;
- }
- // Simplify the full file path to something that can be resolved by Node.
- // If the module could be imported by a directory name, use that directory's name
- var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
- // Get a path that's relative to node_modules or the importing file's path
- moduleSpecifier = getNodeResolvablePath(moduleSpecifier);
- // If the module was found in @types, get the actual Node package name
- return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier);
- function getDirectoryOrExtensionlessFileName(path) {
- // If the file is the main module, it can be imported by the package name
- var packageRootPath = path.substring(0, parts.packageRootIndex);
- var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
- if (host.fileExists(packageJsonPath)) {
- var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
- if (packageJsonContent) {
- var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
- if (mainFileRelative) {
- var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
- if (mainExportFile === getCanonicalFileName(path)) {
- return packageRootPath;
- }
- }
- }
- }
- // We still have a file name - remove the extension
- var fullModulePathWithoutExtension = ts.removeFileExtension(path);
- // If the file is /index, it can be imported by its directory name
- if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") {
- return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
- }
- return fullModulePathWithoutExtension;
- }
- function getNodeResolvablePath(path) {
- var basePath = path.substring(0, parts.topLevelNodeModulesIndex);
- if (sourceDirectory.indexOf(basePath) === 0) {
- // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
- return path.substring(parts.topLevelPackageNameIndex + 1);
- }
- else {
- return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName);
- }
- }
- }
- function getNodeModulePathParts(fullPath) {
- // If fullPath can't be valid module file within node_modules, returns undefined.
- // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
- // Returns indices: ^ ^ ^ ^
- var topLevelNodeModulesIndex = 0;
- var topLevelPackageNameIndex = 0;
- var packageRootIndex = 0;
- var fileNameIndex = 0;
- var States;
- (function (States) {
- States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
- States[States["NodeModules"] = 1] = "NodeModules";
- States[States["Scope"] = 2] = "Scope";
- States[States["PackageContent"] = 3] = "PackageContent";
- })(States || (States = {}));
- var partStart = 0;
- var partEnd = 0;
- var state = 0 /* BeforeNodeModules */;
- while (partEnd >= 0) {
- partStart = partEnd;
- partEnd = fullPath.indexOf("/", partStart + 1);
- switch (state) {
- case 0 /* BeforeNodeModules */:
- if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
- topLevelNodeModulesIndex = partStart;
- topLevelPackageNameIndex = partEnd;
- state = 1 /* NodeModules */;
- }
- break;
- case 1 /* NodeModules */:
- case 2 /* Scope */:
- if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
- state = 2 /* Scope */;
- }
- else {
- packageRootIndex = partEnd;
- state = 3 /* PackageContent */;
- }
- break;
- case 3 /* PackageContent */:
- if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
- state = 1 /* NodeModules */;
- }
- else {
- state = 3 /* PackageContent */;
- }
- break;
- }
- }
- fileNameIndex = partStart;
- return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
- }
- function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
- return ts.firstDefined(rootDirs, function (rootDir) {
- var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
- return isPathRelativeToParent(relativePath) ? undefined : relativePath;
- });
- }
- function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) {
- var noExtension = ts.removeFileExtension(fileName);
- return addJsExtension
- ? noExtension + ".js"
- : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs
- ? ts.removeSuffix(noExtension, "/index")
- : noExtension;
- }
- function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
- var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
- }
- function isPathRelativeToParent(path) {
- return ts.startsWith(path, "..");
- }
function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) {
var fromExistingImport = ts.firstDefined(existingImports, function (_a) {
var declaration = _a.declaration, importKind = _a.importKind;
@@ -99390,7 +100871,7 @@ var ts;
var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier);
var newImportInfos = existingDeclaration
? [existingDeclaration]
- : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences);
+ : 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));
@@ -99848,7 +101329,24 @@ var ts;
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName,
/*questionToken*/ undefined, typeNode,
/*initializer*/ undefined);
- changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
+ if (lastProp) {
+ changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property);
+ }
+ else {
+ changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ }
+ }
+ // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
+ function getNodeToInsertPropertyAfter(cls) {
+ var res;
+ for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ if (!ts.isPropertyDeclaration(member))
+ break;
+ res = member;
+ }
+ return res;
}
function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) {
// Index signatures cannot have the static modifier.
@@ -100160,6 +101658,7 @@ var ts;
ts.Diagnostics._0_is_declared_but_never_used.code,
ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
+ ts.Diagnostics.All_destructured_elements_are_unused.code,
];
codefix.registerCodeFix({
errorCodes: errorCodes,
@@ -100170,9 +101669,13 @@ var ts;
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(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, context.span.start, /*deleted*/ undefined); });
+ if (delDestructure.length) {
+ return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, 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); });
+ var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); });
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));
}
@@ -100183,36 +101686,69 @@ var ts;
return result;
},
fixIds: [fixIdPrefix, fixIdDelete],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- var sourceFile = context.sourceFile;
- var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file);
- switch (context.fixId) {
- case fixIdPrefix:
- if (ts.isIdentifier(token) && canPrefix(token)) {
- tryPrefixDeclaration(changes, diag.code, sourceFile, token);
- }
- break;
- case fixIdDelete:
- var importDecl = tryGetFullImport(diag.file, diag.start);
- if (importDecl) {
- changes.deleteNode(sourceFile, importDecl);
- }
- else {
- tryDeleteDeclaration(changes, sourceFile, token);
- }
- break;
- default:
- ts.Debug.fail(JSON.stringify(context.fixId));
- }
- }); },
+ 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 NodeSet();
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var sourceFile = context.sourceFile;
+ var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file);
+ 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(diag.file, diag.start);
+ if (importDecl) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) {
+ tryDeleteDeclaration(changes, sourceFile, token, deleted);
+ }
+ }
+ break;
+ default:
+ ts.Debug.fail(JSON.stringify(context.fixId));
+ }
+ });
+ },
});
// Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
function tryGetFullImport(sourceFile, pos) {
var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined;
}
+ function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) {
+ var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent))
+ return false;
+ var decl = startToken.parent.parent;
+ switch (decl.kind) {
+ case 231 /* VariableDeclaration */:
+ tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors);
+ break;
+ case 148 /* Parameter */:
+ if (deletedAncestors)
+ deletedAncestors.add(decl);
+ changes.deleteNodeInList(sourceFile, decl);
+ break;
+ case 181 /* BindingElement */:
+ if (deletedAncestors)
+ deletedAncestors.add(decl);
+ changes.deleteNode(sourceFile, decl);
+ break;
+ default:
+ return ts.Debug.assertNever(decl);
+ }
+ return true;
+ }
function getToken(sourceFile, pos) {
- var token = ts.findPrecedingToken(pos, sourceFile);
+ 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;
}
@@ -100237,38 +101773,45 @@ var ts;
}
return false;
}
- function tryDeleteDeclaration(changes, sourceFile, token) {
+ function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors) {
switch (token.kind) {
case 71 /* Identifier */:
- tryDeleteIdentifier(changes, sourceFile, token);
+ tryDeleteIdentifier(changes, sourceFile, token, deletedAncestors);
break;
case 151 /* PropertyDeclaration */:
case 245 /* NamespaceImport */:
+ if (deletedAncestors)
+ deletedAncestors.add(token.parent);
changes.deleteNode(sourceFile, token.parent);
break;
default:
- tryDeleteDefault(changes, sourceFile, token);
+ tryDeleteDefault(changes, sourceFile, token, deletedAncestors);
}
}
- function tryDeleteDefault(changes, sourceFile, token) {
+ function tryDeleteDefault(changes, sourceFile, token, deletedAncestors) {
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);
}
}
- function tryDeleteIdentifier(changes, sourceFile, identifier) {
+ function tryDeleteIdentifier(changes, sourceFile, identifier, deletedAncestors) {
var parent = identifier.parent;
switch (parent.kind) {
case 231 /* VariableDeclaration */:
- tryDeleteVariableDeclaration(changes, sourceFile, parent);
+ tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors);
break;
case 147 /* TypeParameter */:
- var typeParameters = parent.parent.typeParameters;
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent);
if (typeParameters.length === 1) {
- var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false);
- var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false);
+ 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);
@@ -100299,6 +101842,20 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
+ case 181 /* BindingElement */: {
+ var pattern = parent.parent;
+ switch (pattern.kind) {
+ case 180 /* ArrayBindingPattern */:
+ changes.deleteNode(sourceFile, parent); // Don't delete ','
+ break;
+ case 179 /* ObjectBindingPattern */:
+ changes.deleteNodeInList(sourceFile, parent);
+ break;
+ default:
+ return ts.Debug.assertNever(pattern);
+ }
+ break;
+ }
// handle case where 'import a = A;'
case 242 /* ImportEqualsDeclaration */:
var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */);
@@ -100337,7 +101894,7 @@ var ts;
tryDeleteNamedImportBinding(changes, sourceFile, parent);
break;
default:
- tryDeleteDefault(changes, sourceFile, identifier);
+ tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors);
break;
}
}
@@ -100360,15 +101917,19 @@ var ts;
}
}
// token.parent is a variableDeclaration
- function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) {
+ function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) {
switch (varDecl.parent.parent.kind) {
case 219 /* 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;
@@ -100377,6 +101938,8 @@ var ts;
var forOfStatement = varDecl.parent.parent;
ts.Debug.assert(forOfStatement.initializer.kind === 232 /* VariableDeclarationList */);
var forOfInitializer = forOfStatement.initializer;
+ if (deletedAncestors)
+ deletedAncestors.add(forOfInitializer.declarations[0]);
changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral());
break;
case 220 /* ForInStatement */:
@@ -100385,13 +101948,131 @@ var ts;
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);
}
}
}
+ var NodeSet = /** @class */ (function () {
+ function NodeSet() {
+ this.map = ts.createMap();
+ }
+ NodeSet.prototype.add = function (node) {
+ this.map.set(String(ts.getNodeId(node)), node);
+ };
+ NodeSet.prototype.some = function (pred) {
+ return ts.forEachEntry(this.map, pred) || false;
+ };
+ return NodeSet;
+ }());
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "fixUnreachableCode";
+ var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)];
+ },
+ fixIds: [fixId],
+ 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 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 216 /* IfStatement */:
+ if (container.elseStatement) {
+ if (ts.isBlock(statement.parent)) {
+ changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements));
+ }
+ else {
+ changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray));
+ }
+ break;
+ }
+ // falls through
+ case 218 /* WhileStatement */:
+ case 219 /* ForStatement */:
+ changes.deleteNode(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);
+ }
+ }
+ }
+ function shouldRemove(s) {
+ // Don't remove statements that can validly be used before they appear.
+ return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) &&
+ // `var x;` may declare a variable used above
+ !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
+ }
+ function isPurelyTypeDeclaration(s) {
+ switch (s.kind) {
+ case 235 /* InterfaceDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ return true;
+ case 238 /* ModuleDeclaration */:
+ return ts.getModuleInstanceState(s) !== 1 /* Instantiated */;
+ case 237 /* EnumDeclaration */:
+ return ts.hasModifier(s, 2048 /* Const */);
+ }
+ }
+ function sliceAfter(arr, value) {
+ var index = arr.indexOf(value);
+ ts.Debug.assert(index !== -1);
+ return arr.slice(index);
+ }
+ // Calls 'cb' with the start and end of each range where 'pred' is true.
+ function split(arr, pred, cb) {
+ ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); });
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "fixUnusedLabel";
+ var errorCodes = [ts.Diagnostics.Unused_label.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
+ },
+ fixIds: [fixId],
+ 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 labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
+ var pos = token.getStart(sourceFile);
+ var statementPos = labeledStatement.statement.getStart(sourceFile);
+ // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
+ var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
+ : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
+ changes.deleteRange(sourceFile, { pos: pos, end: end });
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -100413,7 +102094,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 === 278 /* JSDocNullableType */) {
+ if (typeNode.kind === 280 /* 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, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -100433,7 +102114,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -100811,16 +102492,16 @@ var ts;
}
var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
var declaration;
- var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); });
+ 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)];
},
fixIds: [fixId],
getAllCodeActions: function (context) {
var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
- var seenFunctions = ts.createMap();
+ 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, seenFunctions);
+ doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen);
});
},
});
@@ -100834,7 +102515,7 @@ var ts;
return ts.Diagnostics.Infer_type_of_0_from_usage;
}
}
- function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) {
+ function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) {
if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) {
return undefined;
}
@@ -100843,17 +102524,18 @@ var ts;
// Variable and Property declarations
case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code:
case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
- if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
+ if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken);
return parent;
}
return undefined;
case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
var symbol = program.getTypeChecker().getSymbolAtLocation(token);
- if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) {
+ if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken);
return symbol.valueDeclaration;
}
+ return undefined;
}
}
var containingFunction = ts.getContainingFunction(token);
@@ -100869,7 +102551,7 @@ var ts;
}
// falls through
case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
- if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) {
+ if (markSeen(containingFunction)) {
var param = ts.cast(parent, ts.isParameter);
annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken);
return param;
@@ -101061,6 +102743,16 @@ var ts;
case 185 /* ElementAccessExpression */:
inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext);
break;
+ case 231 /* 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.
+ addCandidateType(usageContext, checker.getTypeAtLocation(initializer));
+ }
+ break;
+ }
+ }
+ // falls through
default:
return inferTypeFromContextualType(node, checker, usageContext);
}
@@ -101232,7 +102924,7 @@ var ts;
return checker.getStringType();
}
else if (usageContext.candidateTypes) {
- return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */));
+ return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker);
@@ -101349,7 +103041,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -101506,6 +103198,290 @@ var ts;
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
+// Used by importFixes to synthesize import module specifiers.
+/* @internal */
+var ts;
+(function (ts) {
+ var moduleSpecifiers;
+ (function (moduleSpecifiers) {
+ // For each symlink/original for a module, returns a list of ways to import that file.
+ function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) {
+ var compilerOptions = program.getCompilerOptions();
+ var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
+ var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
+ var addJsExtension = usesJsExtensionOnImports(importingSourceFile);
+ var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
+ var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName);
+ return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) {
+ var global = tryGetModuleNameFromAmbientModule(moduleSymbol)
+ || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension)
+ || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory)
+ || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName);
+ if (global) {
+ return [global];
+ }
+ var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension);
+ if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
+ return [relativePath];
+ }
+ var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
+ if (!relativeToBaseUrl) {
+ return [relativePath];
+ }
+ var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension);
+ if (paths) {
+ var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
+ if (fromPaths) {
+ return [fromPaths];
+ }
+ }
+ if (preferences.importModuleSpecifierPreference === "non-relative") {
+ return [importRelativeToBaseUrl];
+ }
+ if (preferences.importModuleSpecifierPreference !== undefined)
+ ts.Debug.assertNever(preferences.importModuleSpecifierPreference);
+ if (isPathRelativeToParent(relativeToBaseUrl)) {
+ return [relativePath];
+ }
+ /*
+ Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl.
+
+ Suppose we have:
+ baseUrl = /base
+ sourceDirectory = /base/a/b
+ moduleFileName = /base/foo/bar
+ Then:
+ relativePath = ../../foo/bar
+ getRelativePathNParents(relativePath) = 2
+ pathFromSourceToBaseUrl = ../../
+ getRelativePathNParents(pathFromSourceToBaseUrl) = 2
+ 2 < 2 = false
+ In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar".
+
+ Suppose we have:
+ baseUrl = /base
+ sourceDirectory = /base/foo/a
+ moduleFileName = /base/foo/bar
+ Then:
+ relativePath = ../a
+ getRelativePathNParents(relativePath) = 1
+ pathFromSourceToBaseUrl = ../../
+ getRelativePathNParents(pathFromSourceToBaseUrl) = 2
+ 1 < 2 = true
+ In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
+ */
+ var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName));
+ var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
+ return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
+ });
+ }
+ moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
+ function usesJsExtensionOnImports(_a) {
+ var imports = _a.imports;
+ return ts.firstDefined(imports, function (_a) {
+ var text = _a.text;
+ return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined;
+ }) || false;
+ }
+ /**
+ * Looks for a existing imports that use symlinks to this module.
+ * Only if no symlink is available, the real path will be used.
+ */
+ function getAllModulePaths(program, _a) {
+ var fileName = _a.fileName;
+ var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) {
+ return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
+ return res && res.resolvedFileName === fileName ? res.originalPath : undefined;
+ });
+ });
+ return symlinks.length === 0 ? [fileName] : symlinks;
+ }
+ function getRelativePathNParents(relativePath) {
+ var components = ts.getPathComponents(relativePath);
+ if (components[0] || components.length === 1)
+ return 0;
+ for (var i = 1; i < components.length; i++) {
+ if (components[i] !== "..")
+ return i - 1;
+ }
+ return components.length - 1;
+ }
+ function tryGetModuleNameFromAmbientModule(moduleSymbol) {
+ var decl = moduleSymbol.valueDeclaration;
+ if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) {
+ return decl.name.text;
+ }
+ }
+ function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
+ for (var key in paths) {
+ for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
+ var patternText_1 = _a[_i];
+ var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
+ var indexOfStar = pattern.indexOf("*");
+ if (indexOfStar === 0 && pattern.length === 1) {
+ continue;
+ }
+ else if (indexOfStar !== -1) {
+ var prefix = pattern.substr(0, indexOfStar);
+ var suffix = pattern.substr(indexOfStar + 1);
+ if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
+ ts.startsWith(relativeToBaseUrl, prefix) &&
+ ts.endsWith(relativeToBaseUrl, suffix)) {
+ var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
+ return key.replace("*", matchedStar);
+ }
+ }
+ else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
+ return key;
+ }
+ }
+ }
+ }
+ function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
+ var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
+ if (normalizedTargetPath === undefined) {
+ return undefined;
+ }
+ var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
+ var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
+ return ts.removeFileExtension(relativePath);
+ }
+ function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
+ var roots = ts.getEffectiveTypeRoots(options, host);
+ return ts.firstDefined(roots, function (unNormalizedTypeRoot) {
+ var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName);
+ if (ts.startsWith(moduleFileName, typeRoot)) {
+ // For a type definition, we can strip `/index` even with classic resolution.
+ return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension);
+ }
+ });
+ }
+ function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) {
+ if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
+ // nothing to do here
+ return undefined;
+ }
+ var parts = getNodeModulePathParts(moduleFileName);
+ if (!parts) {
+ return undefined;
+ }
+ // Simplify the full file path to something that can be resolved by Node.
+ // If the module could be imported by a directory name, use that directory's name
+ var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
+ // Get a path that's relative to node_modules or the importing file's path
+ moduleSpecifier = getNodeResolvablePath(moduleSpecifier);
+ // If the module was found in @types, get the actual Node package name
+ return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier);
+ function getDirectoryOrExtensionlessFileName(path) {
+ // If the file is the main module, it can be imported by the package name
+ var packageRootPath = path.substring(0, parts.packageRootIndex);
+ var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
+ if (host.fileExists(packageJsonPath)) {
+ var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
+ if (packageJsonContent) {
+ var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
+ if (mainFileRelative) {
+ var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
+ if (mainExportFile === getCanonicalFileName(path)) {
+ return packageRootPath;
+ }
+ }
+ }
+ }
+ // We still have a file name - remove the extension
+ var fullModulePathWithoutExtension = ts.removeFileExtension(path);
+ // If the file is /index, it can be imported by its directory name
+ if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") {
+ return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
+ }
+ return fullModulePathWithoutExtension;
+ }
+ function getNodeResolvablePath(path) {
+ var basePath = path.substring(0, parts.topLevelNodeModulesIndex);
+ if (sourceDirectory.indexOf(basePath) === 0) {
+ // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
+ return path.substring(parts.topLevelPackageNameIndex + 1);
+ }
+ else {
+ return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName));
+ }
+ }
+ }
+ function getNodeModulePathParts(fullPath) {
+ // If fullPath can't be valid module file within node_modules, returns undefined.
+ // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
+ // Returns indices: ^ ^ ^ ^
+ var topLevelNodeModulesIndex = 0;
+ var topLevelPackageNameIndex = 0;
+ var packageRootIndex = 0;
+ var fileNameIndex = 0;
+ var States;
+ (function (States) {
+ States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
+ States[States["NodeModules"] = 1] = "NodeModules";
+ States[States["Scope"] = 2] = "Scope";
+ States[States["PackageContent"] = 3] = "PackageContent";
+ })(States || (States = {}));
+ var partStart = 0;
+ var partEnd = 0;
+ var state = 0 /* BeforeNodeModules */;
+ while (partEnd >= 0) {
+ partStart = partEnd;
+ partEnd = fullPath.indexOf("/", partStart + 1);
+ switch (state) {
+ case 0 /* BeforeNodeModules */:
+ if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
+ topLevelNodeModulesIndex = partStart;
+ topLevelPackageNameIndex = partEnd;
+ state = 1 /* NodeModules */;
+ }
+ break;
+ case 1 /* NodeModules */:
+ case 2 /* Scope */:
+ if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
+ state = 2 /* Scope */;
+ }
+ else {
+ packageRootIndex = partEnd;
+ state = 3 /* PackageContent */;
+ }
+ break;
+ case 3 /* PackageContent */:
+ if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
+ state = 1 /* NodeModules */;
+ }
+ else {
+ state = 3 /* PackageContent */;
+ }
+ break;
+ }
+ }
+ fileNameIndex = partStart;
+ return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
+ }
+ function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
+ return ts.firstDefined(rootDirs, function (rootDir) {
+ var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
+ return isPathRelativeToParent(relativePath) ? undefined : relativePath;
+ });
+ }
+ function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) {
+ var noExtension = ts.removeFileExtension(fileName);
+ return addJsExtension
+ ? noExtension + ".js"
+ : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs
+ ? ts.removeSuffix(noExtension, "/index")
+ : noExtension;
+ }
+ function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
+ return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
+ }
+ function isPathRelativeToParent(path) {
+ return ts.startsWith(path, "..");
+ }
+ })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
+})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
@@ -101575,7 +103551,40 @@ var ts;
}
}
function doChange(changes, sourceFile, info) {
- changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (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];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span;
+ var importType = getImportTypeNode(sourceFile, span.start);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start));
+ }); },
+ });
+ function getImportTypeNode(sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ ts.Debug.assert(token.kind === 91 /* ImportKeyword */);
+ ts.Debug.assert(token.parent.kind === 178 /* ImportType */);
+ return token.parent;
+ }
+ function doChange(changes, sourceFile, importType) {
+ var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true);
+ changes.replaceNode(sourceFile, importType, newTypeNode);
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
@@ -101593,7 +103602,7 @@ var ts;
* Exported for tests.
*/
function getAvailableActions(context) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
return undefined;
@@ -101662,7 +103671,7 @@ var ts;
extractSymbol.getAvailableActions = getAvailableActions;
/* Exported for tests */
function getEditsForAction(context, actionName) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
if (parsedFunctionIndexMatch) {
@@ -102774,8 +104783,8 @@ var ts;
i_1++;
}
// Note that we add the current node's type parameters *after* updating the corresponding scope.
- if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) {
- for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) {
+ if (ts.isDeclarationWithTypeParameters(curr)) {
+ for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) {
var typeParameterDecl = _b[_a];
var typeParameter = checker.getTypeAtLocation(typeParameterDecl);
if (allTypeParameterUsages.has(typeParameter.id.toString())) {
@@ -102797,7 +104806,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_17 = function (i) {
+ var _loop_19 = 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
@@ -102837,21 +104846,11 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_17(i);
+ _loop_19(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
- function hasTypeParameters(node) {
- return ts.isDeclarationWithTypeParameters(node) &&
- node.typeParameters !== undefined &&
- node.typeParameters.length > 0;
- }
function isInGenericContext(node) {
- for (; node; node = node.parent) {
- if (hasTypeParameters(node)) {
- return true;
- }
- }
- return false;
+ return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; });
}
function recordTypeParameterUsages(type) {
// PERF: This is potentially very expensive. `type` could be a library type with
@@ -103116,8 +105115,8 @@ 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, startPosition = context.startPosition;
- if (!getConvertibleFieldAtPosition(file, startPosition))
+ var file = context.file;
+ if (!getConvertibleFieldAtPosition(context, file))
return undefined;
return [{
name: actionName,
@@ -103131,27 +105130,46 @@ var ts;
}];
}
function getEditsForAction(context, _actionName) {
- var file = context.file, startPosition = context.startPosition;
- var fieldInfo = getConvertibleFieldAtPosition(file, startPosition);
+ var file = context.file;
+ var fieldInfo = getConvertibleFieldAtPosition(context, file);
if (!fieldInfo)
return undefined;
var isJS = ts.isSourceFileJavaScript(file);
var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor;
+ ts.suppressLeadingAndTrailingTrivia(fieldName);
+ ts.suppressLeadingAndTrailingTrivia(declaration);
+ ts.suppressLeadingAndTrailingTrivia(container);
var isInClassLike = ts.isClassLike(container);
+ // avoid Readonly modifier because it will convert to get accessor
+ var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
var accessorModifiers = isInClassLike
- ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers
+ ? !modifierFlags || modifierFlags & 8 /* Private */
+ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */)
+ : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
: undefined;
var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined;
- updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container);
+ updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
- var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(getAccessor);
insertAccessor(changeTracker, file, getAccessor, declaration, container);
- insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ if (isReadonly) {
+ // readonly modifier only existed in classLikeDeclaration
+ var constructor = ts.getFirstConstructorWithBody(container);
+ if (constructor) {
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ }
+ }
+ else {
+ var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(setAccessor);
+ insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ }
var edits = changeTracker.getChanges();
var renameFilename = file.fileName;
- var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1;
- var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false);
+ var nameNeedRename = renameAccessor ? accessorName : fieldName;
+ var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
+ var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration));
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function isConvertableName(name) {
@@ -103171,24 +105189,32 @@ var ts;
var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined);
return modifiers && ts.createNodeArray(modifiers);
}
- function getConvertibleFieldAtPosition(file, startPosition) {
+ 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);
var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
- // make sure propertyDeclaration have AccessibilityModifier or Static Modifier
- var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */;
- if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
+ // 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)
+ || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
return undefined;
- var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name);
- var accessorName = createPropertyName(declaration.name.text, declaration.name);
- ts.suppressLeadingAndTrailingTrivia(fieldName);
- ts.suppressLeadingAndTrailingTrivia(declaration);
+ var name = declaration.name.text;
+ var startWithUnderscore = startsWithUnderscore(name);
+ var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file.text), declaration.name);
+ var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file.text) : name, declaration.name);
return {
isStatic: ts.hasStaticModifier(declaration),
+ isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent,
+ originalName: declaration.name,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
+ renameAccessor: startWithUnderscore
};
}
function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
@@ -103212,16 +105238,11 @@ var ts;
var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
changeTracker.replaceNode(file, declaration, property);
}
- function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) {
- var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer);
- changeTracker.insertNodeAtClassStart(file, classLikeContainer, property);
- changeTracker.deleteNodeInList(file, declaration);
- }
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
- function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) {
+ function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
if (ts.isPropertyDeclaration(declaration)) {
updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
}
@@ -103229,19 +105250,636 @@ var ts;
updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
}
else {
- updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container);
+ changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
}
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
ts.isParameterPropertyDeclaration(declaration)
? changeTracker.insertNodeAtClassStart(file, container, accessor)
- : changeTracker.insertNodeAfter(file, declaration, accessor);
+ : ts.isPropertyAssignment(declaration)
+ ? changeTracker.insertNodeAfterComma(file, declaration, accessor)
+ : changeTracker.insertNodeAfter(file, declaration, accessor);
+ }
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ if (!constructor.body)
+ return;
+ var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
+ var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); });
+ ts.forEach(referenceEntries, function (entry) {
+ var parent = entry.parent;
+ var accessorName = ts.createIdentifier(fieldName.text);
+ var node = ts.isBinaryExpression(parent)
+ ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
+ : ts.isPropertyAccessExpression(parent)
+ ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
+ : ts.Debug.fail("Unexpected write access token");
+ changeTracker.replaceNode(file, parent, node);
+ });
}
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var refactorName = "Move to a new file";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
+ return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var statements = ts.Debug.assertDefined(getStatementsToMove(context));
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ });
+ function getFirstAndLastStatementToMove(context) {
+ var file = context.file;
+ var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
+ var statements = file.statements;
+ var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
+ if (startNodeIndex === -1)
+ return undefined;
+ // Can't only partially include the start node or be partially into the next node
+ if (range.pos > statements[startNodeIndex].getStart(file))
+ return undefined;
+ var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
+ // Can't be partially into the next node
+ if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
+ return undefined;
+ return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex };
+ }
+ function doChange(oldFile, program, toMove, changes, host) {
+ var checker = program.getTypeChecker();
+ var usage = getUsageInfo(oldFile, toMove.all, checker);
+ var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
+ var extension = ts.extensionFromPath(oldFile.fileName);
+ var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
+ var newFileNameWithExtension = newModuleName + extension;
+ // If previous file was global, this is easy.
+ changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName));
+ addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
+ }
+ // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file.
+ function getStatementsToMove(context) {
+ var statements = context.file.statements;
+ var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast;
+ var all = [];
+ var ranges = [];
+ var rangeToMove = statements.slice(first, afterLast);
+ ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) {
+ for (var i = start; i < afterEnd; i++)
+ all.push(rangeToMove[i]);
+ ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] });
+ });
+ return { all: all, ranges: ranges };
+ }
+ function isPureImport(node) {
+ switch (node.kind) {
+ case 243 /* ImportDeclaration */:
+ return true;
+ case 242 /* ImportEqualsDeclaration */:
+ return !ts.hasModifier(node, 1 /* Export */);
+ case 213 /* VariableStatement */:
+ return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
+ default:
+ return false;
+ }
+ }
+ function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
+ var cfg = program.getCompilerOptions().configFile;
+ if (!cfg)
+ return;
+ var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
+ var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
+ var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
+ var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
+ return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
+ });
+ if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
+ changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
+ }
+ }
+ function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) {
+ var checker = program.getTypeChecker();
+ if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
+ deleteMovedStatements(oldFile, toMove.ranges, changes);
+ return toMove.all;
+ }
+ var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
+ var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax);
+ if (importsFromNewFile) {
+ changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true);
+ }
+ deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
+ deleteMovedStatements(oldFile, toMove.ranges, changes);
+ updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
+ return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
+ }
+ function deleteMovedStatements(sourceFile, moved, changes) {
+ for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
+ var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last;
+ changes.deleteNodeRange(sourceFile, first_1, last_3);
+ }
+ }
+ function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
+ }
+ }
+ function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
+ var checker = program.getTypeChecker();
+ var _loop_20 = function (sourceFile) {
+ if (sourceFile === oldFile)
+ return "continue";
+ var _loop_21 = function (statement) {
+ forEachImportInStatement(statement, function (importNode) {
+ var shouldMove = function (name) {
+ var symbol = ts.isBindingElement(name.parent)
+ ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
+ : ts.skipAlias(checker.getSymbolAtLocation(name), checker);
+ return !!symbol && movedSymbols.has(symbol);
+ };
+ deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
+ var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
+ var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
+ if (newImportDeclaration)
+ changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
+ });
+ };
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ _loop_21(statement);
+ }
+ };
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ _loop_20(sourceFile);
+ }
+ }
+ function moduleSpecifierFromImport(i) {
+ return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier
+ : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
+ : i.initializer.arguments[0]);
+ }
+ function forEachImportInStatement(statement, cb) {
+ if (ts.isImportDeclaration(statement)) {
+ if (ts.isStringLiteral(statement.moduleSpecifier))
+ cb(statement);
+ }
+ else if (ts.isImportEqualsDeclaration(statement)) {
+ if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
+ cb(statement);
+ }
+ }
+ else if (ts.isVariableStatement(statement)) {
+ for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
+ cb(decl);
+ }
+ }
+ }
+ }
+ function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) {
+ var defaultImport;
+ var imports = [];
+ newFileNeedExport.forEach(function (symbol) {
+ if (symbol.escapedName === "default" /* Default */) {
+ defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol));
+ }
+ else {
+ imports.push(symbol.name);
+ }
+ });
+ return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports);
+ }
+ function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) {
+ path = ts.ensurePathIsNonModuleName(path);
+ if (useEs6Imports) {
+ var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
+ return ts.makeImportIfNecessary(defaultImport, specifiers, path);
+ }
+ else {
+ ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module.
+ var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
+ return bindingElements.length
+ ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
+ : undefined;
+ }
+ }
+ function makeVariableStatement(name, type, initializer, flags) {
+ if (flags === void 0) { flags = 2 /* Const */; }
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
+ }
+ function createRequireCall(moduleSpecifier) {
+ return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
+ }
+ function addExports(sourceFile, toMove, needExport, useEs6Exports) {
+ return ts.flatMap(toMove, function (statement) {
+ if (isTopLevelDeclarationStatement(statement) &&
+ !isExported(sourceFile, statement, useEs6Exports) &&
+ forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
+ var exports_2 = addExport(statement, useEs6Exports);
+ if (exports_2)
+ return exports_2;
+ }
+ return statement;
+ });
+ }
+ function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
+ switch (importDecl.kind) {
+ case 243 /* ImportDeclaration */:
+ deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ case 242 /* ImportEqualsDeclaration */:
+ if (isUnused(importDecl.name)) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ break;
+ case 231 /* VariableDeclaration */:
+ deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ default:
+ ts.Debug.assertNever(importDecl);
+ }
+ }
+ function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
+ if (!importDecl.importClause)
+ return;
+ var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ var defaultUnused = !name || isUnused(name);
+ var namedBindingsUnused = !namedBindings ||
+ (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
+ if (defaultUnused && namedBindingsUnused) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (name && defaultUnused) {
+ changes.deleteNode(sourceFile, name);
+ }
+ if (namedBindings) {
+ if (namedBindingsUnused) {
+ changes.deleteNode(sourceFile, namedBindings);
+ }
+ else if (namedBindings.kind === 246 /* NamedImports */) {
+ for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
+ var element = _b[_i];
+ if (isUnused(element.name))
+ changes.deleteNodeInList(sourceFile, element);
+ }
+ }
+ }
+ }
+ }
+ function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
+ var name = varDecl.name;
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ if (isUnused(name)) {
+ changes.deleteNode(sourceFile, name);
+ }
+ break;
+ case 180 /* ArrayBindingPattern */:
+ break;
+ case 179 /* 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);
+ }
+ 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);
+ }
+ }
+ }
+ break;
+ }
+ }
+ function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) {
+ var copiedOldImports = [];
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var oldStatement = _a[_i];
+ forEachImportInStatement(oldStatement, function (i) {
+ ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
+ });
+ }
+ // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
+ var oldFileDefault;
+ var oldFileNamedImports = [];
+ var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
+ newFileImportsFromOldFile.forEach(function (symbol) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (!isTopLevelDeclaration(decl))
+ continue;
+ var name = nameOfTopLevelDeclaration(decl);
+ if (!name)
+ continue;
+ var top = getTopLevelDeclarationStatement(decl);
+ if (markSeenTop(top)) {
+ addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
+ }
+ if (ts.hasModifier(decl, 512 /* Default */)) {
+ oldFileDefault = name;
+ }
+ else {
+ oldFileNamedImports.push(name.text);
+ }
+ }
+ });
+ ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax));
+ return copiedOldImports;
+ }
+ function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
+ var newModuleName = moduleName;
+ for (var i = 1;; i++) {
+ var name = ts.combinePaths(inDirectory, newModuleName + extension);
+ if (!host.fileExists(name))
+ return newModuleName;
+ newModuleName = moduleName + "." + i;
+ }
+ }
+ function getNewModuleName(movedSymbols) {
+ return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
+ }
+ function getUsageInfo(oldFile, toMove, checker) {
+ var movedSymbols = new SymbolSet();
+ var oldImportsNeededByNewFile = new SymbolSet();
+ var newFileImportsFromOldFile = new SymbolSet();
+ for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
+ var statement = toMove_1[_i];
+ forEachTopLevelDeclaration(statement, function (decl) {
+ movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
+ });
+ }
+ for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
+ var statement = toMove_2[_a];
+ forEachReference(statement, checker, function (symbol) {
+ if (!symbol.declarations)
+ return;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (isInImport(decl)) {
+ oldImportsNeededByNewFile.add(symbol);
+ }
+ else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) {
+ newFileImportsFromOldFile.add(symbol);
+ }
+ }
+ });
+ }
+ var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
+ var oldFileImportsFromNewFile = new SymbolSet();
+ for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
+ var statement = _c[_b];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachReference(statement, checker, function (symbol) {
+ if (movedSymbols.has(symbol))
+ oldFileImportsFromNewFile.add(symbol);
+ unusedImportsFromOldFile.delete(symbol);
+ });
+ }
+ return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
+ }
+ // Below should all be utilities
+ function isInImport(decl) {
+ switch (decl.kind) {
+ case 242 /* ImportEqualsDeclaration */:
+ case 247 /* ImportSpecifier */:
+ case 244 /* ImportClause */:
+ return true;
+ case 231 /* VariableDeclaration */:
+ return isVariableDeclarationInImport(decl);
+ case 181 /* BindingElement */:
+ return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
+ default:
+ return false;
+ }
+ }
+ function isVariableDeclarationInImport(decl) {
+ return ts.isSourceFile(decl.parent.parent.parent) &&
+ decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
+ }
+ function filterImport(i, moduleSpecifier, keep) {
+ switch (i.kind) {
+ case 243 /* ImportDeclaration */: {
+ var clause = i.importClause;
+ if (!clause)
+ return undefined;
+ var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
+ var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
+ return defaultImport || namedBindings
+ ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
+ : undefined;
+ }
+ case 242 /* ImportEqualsDeclaration */:
+ return keep(i.name) ? i : undefined;
+ case 231 /* VariableDeclaration */: {
+ var name = filterBindingName(i.name, keep);
+ return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
+ }
+ default:
+ return ts.Debug.assertNever(i);
+ }
+ }
+ function filterNamedBindings(namedBindings, keep) {
+ if (namedBindings.kind === 245 /* NamespaceImport */) {
+ return keep(namedBindings.name) ? namedBindings : undefined;
+ }
+ else {
+ var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
+ return newElements.length ? ts.createNamedImports(newElements) : undefined;
+ }
+ }
+ function filterBindingName(name, keep) {
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ return keep(name) ? name : undefined;
+ case 180 /* ArrayBindingPattern */:
+ return name;
+ case 179 /* 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;
+ }
+ }
+ }
+ function forEachReference(node, checker, onReference) {
+ node.forEachChild(function cb(node) {
+ if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
+ var sym = checker.getSymbolAtLocation(node);
+ if (sym)
+ onReference(sym);
+ }
+ else {
+ node.forEachChild(cb);
+ }
+ });
+ }
+ var SymbolSet = /** @class */ (function () {
+ function SymbolSet() {
+ this.map = ts.createMap();
+ }
+ SymbolSet.prototype.add = function (symbol) {
+ this.map.set(String(ts.getSymbolId(symbol)), symbol);
+ };
+ SymbolSet.prototype.has = function (symbol) {
+ return this.map.has(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.delete = function (symbol) {
+ this.map.delete(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ SymbolSet.prototype.forEachEntry = function (cb) {
+ return ts.forEachEntry(this.map, cb);
+ };
+ SymbolSet.prototype.clone = function () {
+ var clone = new SymbolSet();
+ ts.copyEntries(this.map, clone.map);
+ return clone;
+ };
+ return SymbolSet;
+ }());
+ function isTopLevelDeclaration(node) {
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
+ }
+ function isTopLevelDeclarationStatement(node) {
+ ts.Debug.assert(ts.isSourceFile(node.parent));
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
+ }
+ function isNonVariableTopLevelDeclaration(node) {
+ switch (node.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function forEachTopLevelDeclaration(statement, cb) {
+ switch (statement.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return cb(statement);
+ case 213 /* VariableStatement */:
+ return ts.forEach(statement.declarationList.declarations, cb);
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */
+ ? cb(statement)
+ : undefined;
+ }
+ }
+ }
+ function nameOfTopLevelDeclaration(d) {
+ return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
+ }
+ function getTopLevelDeclarationStatement(d) {
+ return ts.isVariableDeclaration(d) ? d.parent.parent : d;
+ }
+ function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
+ if (isExported(sourceFile, decl, useEs6Exports))
+ return;
+ if (useEs6Exports) {
+ if (!ts.isExpressionStatement(decl))
+ changes.insertExportModifier(sourceFile, decl);
+ }
+ else {
+ var names = getNamesToExportInCommonJS(decl);
+ if (names.length !== 0)
+ changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
+ }
+ }
+ function isExported(sourceFile, decl, useEs6Exports) {
+ if (useEs6Exports) {
+ return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
+ }
+ else {
+ return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
+ }
+ }
+ function addExport(decl, useEs6Exports) {
+ return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
+ }
+ function addEs6Export(d) {
+ var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
+ switch (d.kind) {
+ case 233 /* FunctionDeclaration */:
+ return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
+ case 234 /* ClassDeclaration */:
+ return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 213 /* VariableStatement */:
+ return ts.updateVariableStatement(d, modifiers, d.declarationList);
+ case 238 /* ModuleDeclaration */:
+ return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
+ case 237 /* EnumDeclaration */:
+ return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
+ case 236 /* TypeAliasDeclaration */:
+ return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
+ case 235 /* InterfaceDeclaration */:
+ return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 242 /* ImportEqualsDeclaration */:
+ return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ return ts.Debug.assertNever(d);
+ }
+ }
+ function addCommonjsExport(decl) {
+ return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment));
+ }
+ function getNamesToExportInCommonJS(decl) {
+ switch (decl.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ return [decl.name.text];
+ case 213 /* VariableStatement */:
+ return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return undefined;
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ ts.Debug.assertNever(decl);
+ }
+ }
+ /** Creates `exports.x = x;` */
+ function createExportAssignment(name) {
+ return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name)));
+ }
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var sourcemaps;
(function (sourcemaps) {
@@ -103563,7 +106201,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 297 /* LastJSDocNode */; });
return child.kind < 145 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -103633,7 +106271,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(298 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
@@ -104156,6 +106794,9 @@ var ts;
HostCache.prototype.compilationSettings = function () {
return this._compilationSettings;
};
+ HostCache.prototype.getProjectReferences = function () {
+ return this.host.getProjectReferences && this.host.getProjectReferences();
+ };
HostCache.prototype.createEntry = function (fileName, path) {
var entry;
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
@@ -104185,9 +106826,18 @@ var ts;
return ts.isString(info) ? undefined : info;
};
HostCache.prototype.getRootFileNames = function () {
- return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) {
- return ts.isString(entry) ? entry : entry.hostFileName;
+ var names = [];
+ this.fileNameToEntry.forEach(function (entry) {
+ if (ts.isString(entry)) {
+ names.push(entry);
+ }
+ else {
+ if (entry.scriptKind !== 6 /* JSON */) {
+ names.push(entry.hostFileName);
+ }
+ }
});
+ return names;
};
HostCache.prototype.getVersion = function (path) {
var file = this.getHostFileInformation(path);
@@ -104363,6 +107013,7 @@ var ts;
}
ts.createSourceFileLikeCache = createSourceFileLikeCache;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
var syntaxTreeCache = new SyntaxTreeCache(host);
@@ -104466,7 +107117,14 @@ var ts;
};
}
var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
- program = ts.createProgram(rootFileNames, newSettings, compilerHost, program);
+ var options = {
+ rootNames: rootFileNames,
+ options: newSettings,
+ host: compilerHost,
+ oldProgram: program,
+ projectReferences: hostCache.getProjectReferences()
+ };
+ program = ts.createProgram(options);
// hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
// It needs to be cleared to allow all collected snapshots to be released
hostCache = undefined;
@@ -104670,6 +107328,11 @@ var ts;
}
return checker.getSymbolAtLocation(node);
}
+ function toLineColumnOffset(fileName, position) {
+ var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
+ var file = program.getSourceFile(path) || sourcemappedFileCache.get(path);
+ 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 base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
@@ -104741,27 +107404,28 @@ var ts;
}
function makeGetTargetOfMappedPosition(extract, create) {
return getTargetOfMappedPosition;
- function getTargetOfMappedPosition(input) {
+ function getTargetOfMappedPosition(input, original) {
+ if (original === void 0) { original = input; }
var info = extract(input);
if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) {
- var file = program.getSourceFile(info.fileName);
- if (!file) {
+ var file_18 = program.getSourceFile(info.fileName);
+ if (!file_18) {
var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName);
- file = sourcemappedFileCache.get(path);
+ file_18 = sourcemappedFileCache.get(path);
}
- if (!file) {
+ if (!file_18) {
return input;
}
- var mapper = getSourceMapper(info.fileName, file);
+ var mapper = getSourceMapper(info.fileName, file_18);
var newLoc = mapper.getOriginalPosition(info);
if (newLoc === info)
return input;
- return getTargetOfMappedPosition(create(newLoc, input));
+ return getTargetOfMappedPosition(create(newLoc, input, original), original);
}
return input;
}
}
- var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({
+ var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({
containerKind: info.containerKind,
containerName: info.containerName,
fileName: newLoc.fileName,
@@ -104770,10 +107434,12 @@ var ts;
textSpan: {
start: newLoc.position,
length: info.textSpan.length
- }
+ },
+ originalFileName: original.fileName,
+ originalTextSpan: original.textSpan
}); });
function getTargetOfMappedDeclarationFiles(infos) {
- return ts.map(infos, getTargetOfMappedDeclarationInfo);
+ return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); });
}
/// Goto definition
function getDefinitionAtPosition(fileName, position) {
@@ -104806,10 +107472,12 @@ var ts;
textSpan: {
start: newLoc.position,
length: info.textSpan.length
- }
+ },
+ originalFileName: info.fileName,
+ originalTextSpan: info.textSpan
}); });
function getTargetOfMappedImplementationLocations(infos) {
- return ts.map(infos, getTargetOfMappedImplementationLocation);
+ return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); });
}
function getImplementationAtPosition(fileName, position) {
synchronizeHostData();
@@ -105317,8 +107985,8 @@ var ts;
getProgram: getProgram,
getApplicableRefactors: getApplicableRefactors,
getEditsForRefactor: getEditsForRefactor,
+ toLineColumnOffset: toLineColumnOffset
};
- var _a;
}
ts.createLanguageService = createLanguageService;
/* @internal */
@@ -105389,20 +108057,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_6 = [];
+ var result_7 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_6.push(symbol);
+ result_7.push(symbol);
}
});
- return result_6;
+ return result_7;
}
if (symbol) {
- result_6.push(symbol);
- return result_6;
+ result_7.push(symbol);
+ return result_7;
}
}
return undefined;
@@ -105469,7 +108137,7 @@ var ts;
return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
- return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
+ return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
@@ -105484,7 +108152,7 @@ var ts;
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
- return spanInNode(ts.findNextToken(node, node.parent));
+ return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
}
function spanInNode(node) {
if (node) {
@@ -106823,5 +109491,3 @@ var TypeScript;
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-
-//# sourceMappingURL=typescriptServices.js.map
diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts
index 6c81f213986..d237cc98eee 100644
--- a/lib/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -337,32 +337,36 @@ declare namespace ts {
EnumMember = 272,
SourceFile = 273,
Bundle = 274,
- JSDocTypeExpression = 275,
- JSDocAllType = 276,
- JSDocUnknownType = 277,
- JSDocNullableType = 278,
- JSDocNonNullableType = 279,
- JSDocOptionalType = 280,
- JSDocFunctionType = 281,
- JSDocVariadicType = 282,
- JSDocComment = 283,
- JSDocTypeLiteral = 284,
- JSDocTag = 285,
- JSDocAugmentsTag = 286,
- JSDocClassTag = 287,
- JSDocParameterTag = 288,
- JSDocReturnTag = 289,
- JSDocTypeTag = 290,
- JSDocTemplateTag = 291,
- JSDocTypedefTag = 292,
- JSDocPropertyTag = 293,
- SyntaxList = 294,
- NotEmittedStatement = 295,
- PartiallyEmittedExpression = 296,
- CommaListExpression = 297,
- MergeDeclarationMarker = 298,
- EndOfDeclarationMarker = 299,
- Count = 300,
+ UnparsedSource = 275,
+ InputFiles = 276,
+ JSDocTypeExpression = 277,
+ JSDocAllType = 278,
+ JSDocUnknownType = 279,
+ JSDocNullableType = 280,
+ JSDocNonNullableType = 281,
+ JSDocOptionalType = 282,
+ JSDocFunctionType = 283,
+ JSDocVariadicType = 284,
+ JSDocComment = 285,
+ JSDocTypeLiteral = 286,
+ JSDocSignature = 287,
+ JSDocTag = 288,
+ JSDocAugmentsTag = 289,
+ JSDocClassTag = 290,
+ JSDocCallbackTag = 291,
+ JSDocParameterTag = 292,
+ JSDocReturnTag = 293,
+ JSDocTypeTag = 294,
+ JSDocTemplateTag = 295,
+ JSDocTypedefTag = 296,
+ JSDocPropertyTag = 297,
+ SyntaxList = 298,
+ NotEmittedStatement = 299,
+ PartiallyEmittedExpression = 300,
+ CommaListExpression = 301,
+ MergeDeclarationMarker = 302,
+ EndOfDeclarationMarker = 303,
+ Count = 304,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -388,10 +392,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 145,
- FirstJSDocNode = 275,
- LastJSDocNode = 293,
- FirstJSDocTagNode = 285,
- LastJSDocTagNode = 293
+ FirstJSDocNode = 277,
+ LastJSDocNode = 297,
+ FirstJSDocTagNode = 288,
+ LastJSDocTagNode = 297
}
enum NodeFlags {
None = 0,
@@ -415,6 +419,7 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 131072,
HasAggregatedChildData = 262144,
JSDoc = 2097152,
+ JsonFile = 16777216,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
@@ -1149,7 +1154,7 @@ declare namespace ts {
kind: SyntaxKind.NotEmittedStatement;
}
/**
- * A list of comma-seperated expressions. This node is only created by transformations.
+ * A list of comma-separated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
@@ -1277,7 +1282,7 @@ declare namespace ts {
block: Block;
}
type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode;
- type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag;
+ type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature;
interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer {
kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression;
name?: Identifier;
@@ -1534,6 +1539,19 @@ declare namespace ts {
name?: Identifier;
typeExpression?: JSDocTypeExpression | JSDocTypeLiteral;
}
+ interface JSDocCallbackTag extends JSDocTag, NamedDeclaration {
+ parent: JSDoc;
+ kind: SyntaxKind.JSDocCallbackTag;
+ fullName?: JSDocNamespaceDeclaration | Identifier;
+ name?: Identifier;
+ typeExpression: JSDocSignature;
+ }
+ interface JSDocSignature extends JSDocType, Declaration {
+ kind: SyntaxKind.JSDocSignature;
+ typeParameters?: ReadonlyArray;
+ parameters: ReadonlyArray;
+ type: JSDocReturnTag | undefined;
+ }
interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
parent: JSDoc;
name: EntityName;
@@ -1644,12 +1662,32 @@ declare namespace ts {
}
interface Bundle extends Node {
kind: SyntaxKind.Bundle;
+ prepends: ReadonlyArray;
sourceFiles: ReadonlyArray;
}
+ interface InputFiles extends Node {
+ kind: SyntaxKind.InputFiles;
+ javascriptText: string;
+ declarationText: string;
+ }
+ interface UnparsedSource extends Node {
+ kind: SyntaxKind.UnparsedSource;
+ text: string;
+ }
interface JsonSourceFile extends SourceFile {
- jsonObject?: ObjectLiteralExpression;
+ statements: NodeArray;
+ }
+ interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
}
+ interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
+ kind: SyntaxKind.PrefixUnaryExpression;
+ operator: SyntaxKind.MinusToken;
+ operand: NumericLiteral;
+ }
+ interface JsonObjectExpressionStatement extends ExpressionStatement {
+ expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
+ }
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
@@ -1705,12 +1743,19 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
+ getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
+ }
+ interface ResolvedProjectReference {
+ commandLine: ParsedCommandLine;
+ sourceFile: SourceFile;
}
interface CustomTransformers {
- /** Custom transformers to evaluate before built-in transformations. */
+ /** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory[];
- /** Custom transformers to evaluate after built-in transformations. */
+ /** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory[];
+ /** Custom transformers to evaluate after built-in .d.ts transformations. */
+ afterDeclarations?: TransformerFactory[];
}
interface SourceMapSpan {
/** Line number in the .js file. */
@@ -1853,7 +1898,9 @@ declare namespace ts {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
+ GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
+ ForbidIndexedAccessSymbolReferences = 16,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
UseOnlyExternalAliasing = 128,
@@ -2217,6 +2264,7 @@ declare namespace ts {
objectType: Type;
indexType: Type;
constraint?: Type;
+ simplified?: Type;
}
type TypeVariable = TypeParameter | IndexedAccessType;
interface IndexType extends InstantiableType {
@@ -2251,7 +2299,7 @@ declare namespace ts {
Construct = 1
}
interface Signature {
- declaration?: SignatureDeclaration;
+ declaration?: SignatureDeclaration | JSDocSignature;
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
@@ -2274,7 +2322,9 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
- interface JsFileExtensionInfo {
+ /** @deprecated Use FileExtensionInfo instead. */
+ type JsFileExtensionInfo = FileExtensionInfo;
+ interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
@@ -2322,7 +2372,17 @@ declare namespace ts {
interface PluginImport {
name: string;
}
- type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined;
+ interface ProjectReference {
+ /** A normalized path on disk */
+ path: string;
+ /** The path as the user originally wrote it */
+ originalPath?: string;
+ /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
+ prepend?: boolean;
+ /** True if it is intended that this reference form a circularity */
+ circular?: boolean;
+ }
+ type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined;
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -2378,6 +2438,7 @@ declare namespace ts {
project?: string;
reactNamespace?: string;
jsxFactory?: string;
+ composite?: boolean;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2393,11 +2454,12 @@ declare namespace ts {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
+ resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
- [option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
+ [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
interface TypeAcquisition {
enableAutoDiscovery?: boolean;
@@ -2437,7 +2499,12 @@ declare namespace ts {
TS = 3,
TSX = 4,
External = 5,
- JSON = 6
+ JSON = 6,
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ Deferred = 7
}
enum ScriptTarget {
ES3 = 0,
@@ -2447,6 +2514,7 @@ declare namespace ts {
ES2017 = 4,
ES2018 = 5,
ESNext = 6,
+ JSON = 100,
Latest = 6
}
enum LanguageVariant {
@@ -2458,6 +2526,7 @@ declare namespace ts {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
+ projectReferences?: ReadonlyArray;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike;
@@ -2469,8 +2538,17 @@ declare namespace ts {
}
interface ExpandResult {
fileNames: string[];
+ projectReferences: ReadonlyArray | undefined;
wildcardDirectories: MapLike;
}
+ interface CreateProgramOptions {
+ rootNames: ReadonlyArray;
+ options: CompilerOptions;
+ projectReferences?: ReadonlyArray;
+ host?: CompilerHost;
+ oldProgram?: Program;
+ configFileParsingDiagnostics?: ReadonlyArray;
+ }
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string | undefined;
@@ -2561,6 +2639,7 @@ declare namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
+ readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
@@ -2918,10 +2997,11 @@ declare namespace ts {
readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[];
getModifiedTime?(path: string): Date;
/**
- * This should be cryptographically secure.
* A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm)
*/
createHash?(data: string): string;
+ /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */
+ createSHA256Hash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
@@ -3298,6 +3378,8 @@ declare namespace ts {
function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag;
function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag;
function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral;
+ function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag;
+ function isJSDocSignature(node: Node): node is JSDocSignature;
}
declare namespace ts {
/**
@@ -3423,6 +3505,8 @@ declare namespace ts {
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
+ function createStringLiteral(text: string): StringLiteral;
+ function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
/** Create a unique temporary variable. */
@@ -3727,8 +3811,10 @@ declare namespace ts {
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression;
- function createBundle(sourceFiles: ReadonlyArray): Bundle;
- function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle;
+ function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
+ function createUnparsedSourceFile(text: string): UnparsedSource;
+ function createInputFiles(javascript: string, declaration: string): InputFiles;
+ function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression;
function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression;
@@ -3792,6 +3878,7 @@ declare namespace ts {
function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined;
function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T;
function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T;
+ function moveSyntheticComments(node: T, original: Node): T;
/**
* Gets the constant value to emit for an expression.
*/
@@ -3935,6 +4022,7 @@ declare namespace ts {
* @param configFileParsingDiagnostics - error during config file parsing
* @returns A 'Program' object.
*/
+ function createProgram(createProgramOptions: CreateProgramOptions): Program;
function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program;
}
declare namespace ts {
@@ -4074,7 +4162,6 @@ declare namespace ts {
function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram;
}
declare namespace ts {
- type DiagnosticReporter = (diagnostic: Diagnostic) => void;
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T;
@@ -4137,15 +4224,6 @@ declare namespace ts {
/** Compiler options */
options: CompilerOptions;
}
- /**
- * Reports config file diagnostics
- */
- interface ConfigFileDiagnosticsReporter {
- /**
- * Reports unrecoverable error when parsing config file
- */
- onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
- }
/**
* Host to create watch with config file
*/
@@ -4192,6 +4270,26 @@ declare namespace ts {
}
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine;
+ type DiagnosticReporter = (diagnostic: Diagnostic) => void;
+ /**
+ * Reports config file diagnostics
+ */
+ interface ConfigFileDiagnosticsReporter {
+ /**
+ * Reports unrecoverable error when parsing config file
+ */
+ onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
+ }
+ /**
+ * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
+ */
+ interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
+ getCurrentDirectory(): string;
+ }
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -4213,7 +4311,7 @@ declare namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
- function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile;
+ function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
/**
* Convert the json syntax tree into the json value
*/
@@ -4225,7 +4323,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
/**
* Parse the contents of a config file (tsconfig.json).
* @param jsonNode The contents of the config file to parse
@@ -4233,7 +4331,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -4252,7 +4350,7 @@ declare namespace ts {
getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number;
getFullStart(): number;
getEnd(): number;
- getWidth(sourceFile?: SourceFile): number;
+ getWidth(sourceFile?: SourceFileLike): number;
getFullWidth(): number;
getLeadingTriviaWidth(sourceFile?: SourceFile): number;
getFullText(sourceFile?: SourceFile): string;
@@ -4364,6 +4462,7 @@ declare namespace ts {
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
+ getProjectReferences?(): ReadonlyArray | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -4378,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
+ getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -4393,6 +4493,7 @@ declare namespace ts {
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
+ readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -4441,6 +4542,7 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan;
+ toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray;
getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions;
applyCodeActionCommand(action: CodeActionCommand): Promise;
@@ -4465,9 +4567,10 @@ declare namespace ts {
fileName: string;
}
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. */
- triggerCharacter?: string;
+ triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
@@ -4534,6 +4637,7 @@ declare namespace ts {
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
+ isNewFile?: boolean;
}
interface CodeAction {
/** Description of the code action to display in the UI of the editor */
@@ -4620,6 +4724,12 @@ declare namespace ts {
interface DocumentSpan {
textSpan: TextSpan;
fileName: string;
+ /**
+ * If the span represents a location that was remapped (e.g. via a .d.ts.map file),
+ * then the original filename and span will be specified here
+ */
+ originalTextSpan?: TextSpan;
+ originalFileName?: string;
}
interface RenameLocation extends DocumentSpan {
}
@@ -4717,9 +4827,7 @@ declare namespace ts {
insertSpaceBeforeTypeAnnotation?: boolean;
indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean;
}
- interface DefinitionInfo {
- fileName: string;
- textSpan: TextSpan;
+ interface DefinitionInfo extends DocumentSpan {
kind: ScriptElementKind;
name: string;
containerKind: ScriptElementKind;
@@ -4865,6 +4973,20 @@ declare namespace ts {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
+ /**
+ * Classification of the contents of the span
+ */
+ kind: OutliningSpanKind;
+ }
+ enum OutliningSpanKind {
+ /** Single or multi-line comments */
+ Comment = "comment",
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ Region = "region",
+ /** Declarations and expressions */
+ Code = "code",
+ /** Contiguous blocks of import declarations */
+ Imports = "imports"
}
enum OutputFileType {
JavaScript = 0,
@@ -4988,7 +5110,9 @@ declare namespace ts {
/**
*
*/
- jsxAttribute = "JSX attribute"
+ jsxAttribute = "JSX attribute",
+ /** String literal */
+ string = "string"
}
enum ScriptElementKindModifier {
none = "",
diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js
index 86c2e32ef0e..5a20323ef59 100644
--- a/lib/typescriptServices.js
+++ b/lib/typescriptServices.js
@@ -350,38 +350,42 @@ var ts;
// Top-level nodes
SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile";
SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 287] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 288] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 289] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 290] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 291] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 292] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 293] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 294] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 295] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 296] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 297] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 298] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 299] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 300] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 301] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 302] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 303] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 300] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 304] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
@@ -408,10 +412,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 297] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 288] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 297] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -451,6 +455,7 @@ var ts;
NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
/* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
/* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
+ NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile";
NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
@@ -513,10 +518,9 @@ var ts;
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
// Flags
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
/* @internal */
var TokenFlags;
@@ -591,9 +595,9 @@ var ts;
// Options
NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- // empty space
+ NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
- // empty space
+ NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
@@ -885,6 +889,8 @@ var ts;
TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType";
TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive";
/* @internal */
+ TypeFlags[TypeFlags["UnionOfUnitTypes"] = 268435456] = "UnionOfUnitTypes";
+ /* @internal */
TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable";
@@ -920,6 +926,8 @@ var ts;
TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable";
TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit";
/* @internal */
+ TypeFlags[TypeFlags["NotUnit"] = 8374815] = "NotUnit";
+ /* @internal */
TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening";
/* @internal */
TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags";
@@ -1072,6 +1080,11 @@ var ts;
ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
ScriptKind[ScriptKind["External"] = 5] = "External";
ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
})(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
var ScriptTarget;
(function (ScriptTarget) {
@@ -1082,6 +1095,7 @@ var ts;
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
@@ -1894,8 +1908,8 @@ var ts;
}
ts.findLast = findLast;
/** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
- function findIndex(array, predicate) {
- for (var i = 0; i < array.length; i++) {
+ function findIndex(array, predicate, startIndex) {
+ for (var i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
@@ -1903,6 +1917,15 @@ var ts;
return -1;
}
ts.findIndex = findIndex;
+ function findLastIndex(array, predicate, startIndex) {
+ for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
+ if (predicate(array[i], i)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ ts.findLastIndex = findLastIndex;
/**
* Returns the first truthy result of `callback`, or else fails.
* This is like `forEach`, but never returns undefined.
@@ -2255,6 +2278,24 @@ var ts;
return false;
}
ts.some = some;
+ /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
+ function getRangesWhere(arr, pred, cb) {
+ var start;
+ for (var i = 0; i < arr.length; i++) {
+ if (pred(arr[i])) {
+ start = start === undefined ? i : start;
+ }
+ else {
+ if (start !== undefined) {
+ cb(start, i);
+ start = undefined;
+ }
+ }
+ }
+ if (start !== undefined)
+ cb(start, arr.length);
+ }
+ ts.getRangesWhere = getRangesWhere;
function concatenate(array1, array2) {
if (!some(array2))
return array1;
@@ -2498,6 +2539,23 @@ var ts;
return to;
}
ts.addRange = addRange;
+ /**
+ * Appends a range of value to begin of an array, returning the array.
+ *
+ * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array
+ * is created if `value` was appended.
+ * @param from The values to append to the array. If `from` is `undefined`, nothing is
+ * appended. If an element of `from` is `undefined`, that element is not appended.
+ */
+ function prependRange(to, from) {
+ if (from === undefined || from.length === 0)
+ return to;
+ if (to === undefined)
+ return from.slice();
+ to.unshift.apply(to, from);
+ return to;
+ }
+ ts.prependRange = prependRange;
/**
* @return Whether the value was added.
*/
@@ -2747,17 +2805,18 @@ var ts;
}
ts.getOwnValues = getOwnValues;
function arrayFrom(iterator, map) {
+ var _a;
var result = [];
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
result.push(map ? map(value) : value);
}
return result;
- var _b;
}
ts.arrayFrom = arrayFrom;
function forEachEntry(map, callback) {
+ var _a;
var iterator = map.entries();
- for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
var key = pair[0], value = pair[1];
var result = callback(value, key);
if (result) {
@@ -2765,19 +2824,18 @@ var ts;
}
}
return undefined;
- var _b;
}
ts.forEachEntry = forEachEntry;
function forEachKey(map, callback) {
+ var _a;
var iterator = map.keys();
- for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
var result = callback(key);
if (result) {
return result;
}
}
return undefined;
- var _b;
}
ts.forEachKey = forEachKey;
function copyEntries(source, target) {
@@ -3334,11 +3392,11 @@ var ts;
comparer(a[key], b[key]);
}
ts.compareProperties = compareProperties;
- function getDiagnosticFileName(diagnostic) {
- return diagnostic.file ? diagnostic.file.fileName : undefined;
+ function getDiagnosticFilePath(diagnostic) {
+ return diagnostic.file ? diagnostic.file.path : undefined;
}
function compareDiagnostics(d1, d2) {
- return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
+ return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
@@ -3370,106 +3428,6 @@ var ts;
// We still have one chain remaining. The shorter chain should come first.
return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */;
}
- function normalizeSlashes(path) {
- return path.replace(/\\/g, "/");
- }
- ts.normalizeSlashes = normalizeSlashes;
- /**
- * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
- */
- function getRootLength(path) {
- if (path.charCodeAt(0) === 47 /* slash */) {
- if (path.charCodeAt(1) !== 47 /* slash */)
- return 1;
- var p1 = path.indexOf("/", 2);
- if (p1 < 0)
- return 2;
- var p2 = path.indexOf("/", p1 + 1);
- if (p2 < 0)
- return p1 + 1;
- return p2 + 1;
- }
- if (path.charCodeAt(1) === 58 /* colon */) {
- if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */)
- return 3;
- }
- // Per RFC 1738 'file' URI schema has the shape file:///
- // if is omitted then it is assumed that host value is 'localhost',
- // however slash after the omitted is not removed.
- // file:///folder1/file1 - this is a correct URI
- // file://folder2/file2 - this is an incorrect URI
- if (path.lastIndexOf("file:///", 0) === 0) {
- return "file:///".length;
- }
- var idx = path.indexOf("://");
- if (idx !== -1) {
- return idx + "://".length;
- }
- return 0;
- }
- ts.getRootLength = getRootLength;
- /**
- * Internally, we represent paths as strings with '/' as the directory separator.
- * When we make system calls (eg: LanguageServiceHost.getDirectory()),
- * we expect the host to correctly handle paths in our specified format.
- */
- ts.directorySeparator = "/";
- var directorySeparatorCharCode = 47 /* slash */;
- function getNormalizedParts(normalizedSlashedPath, rootLength) {
- var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator);
- var normalized = [];
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
- var part = parts_1[_i];
- if (part !== ".") {
- if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") {
- normalized.pop();
- }
- else {
- // A part may be an empty string (which is 'falsy') if the path had consecutive slashes,
- // e.g. "path//file.ts". Drop these before re-joining the parts.
- if (part) {
- normalized.push(part);
- }
- }
- }
- }
- return normalized;
- }
- function normalizePath(path) {
- return normalizePathAndParts(path).path;
- }
- ts.normalizePath = normalizePath;
- function normalizePathAndParts(path) {
- path = normalizeSlashes(path);
- var rootLength = getRootLength(path);
- var root = path.substr(0, rootLength);
- var parts = getNormalizedParts(path, rootLength);
- if (parts.length) {
- var joinedParts = root + parts.join(ts.directorySeparator);
- return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts };
- }
- else {
- return { path: root, parts: parts };
- }
- }
- ts.normalizePathAndParts = normalizePathAndParts;
- /** A path ending with '/' refers to a directory only, never a file. */
- function pathEndsWithDirectorySeparator(path) {
- return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
- }
- ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator;
- function getDirectoryPath(path) {
- return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator)));
- }
- ts.getDirectoryPath = getDirectoryPath;
- function isUrl(path) {
- return path && !isRootedDiskPath(path) && stringContains(path, "://");
- }
- ts.isUrl = isUrl;
- function pathIsRelative(path) {
- return /^\.\.?($|[\\/])/.test(path);
- }
- ts.pathIsRelative = pathIsRelative;
function getEmitScriptTarget(compilerOptions) {
return compilerOptions.target || 0 /* ES3 */;
}
@@ -3501,6 +3459,10 @@ var ts;
: moduleKind === ts.ModuleKind.System;
}
ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
+ function getEmitDeclarations(compilerOptions) {
+ return !!(compilerOptions.declaration || compilerOptions.composite);
+ }
+ ts.getEmitDeclarations = getEmitDeclarations;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
}
@@ -3521,202 +3483,455 @@ var ts;
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ //
+ // Paths
+ //
+ /**
+ * Internally, we represent paths as strings with '/' as the directory separator.
+ * When we make system calls (eg: LanguageServiceHost.getDirectory()),
+ * we expect the host to correctly handle paths in our specified format.
+ */
+ ts.directorySeparator = "/";
+ var altDirectorySeparator = "\\";
+ var urlSchemeSeparator = "://";
+ var backslashRegExp = /\\/g;
+ /**
+ * Normalize path separators.
+ */
+ function normalizeSlashes(path) {
+ return path.replace(backslashRegExp, ts.directorySeparator);
+ }
+ ts.normalizeSlashes = normalizeSlashes;
+ function isVolumeCharacter(charCode) {
+ return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
+ (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
+ }
+ function getFileUrlVolumeSeparatorEnd(url, start) {
+ var ch0 = url.charCodeAt(start);
+ if (ch0 === 58 /* colon */)
+ return start + 1;
+ if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
+ var ch2 = url.charCodeAt(start + 2);
+ if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
+ return start + 3;
+ }
+ return -1;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ * If the root is part of a URL, the twos-complement of the root length is returned.
+ */
+ function getEncodedRootLength(path) {
+ if (!path)
+ return 0;
+ var ch0 = path.charCodeAt(0);
+ // POSIX or UNC
+ if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
+ if (path.charCodeAt(1) !== ch0)
+ return 1; // POSIX: "/" (or non-normalized "\")
+ var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
+ if (p1 < 0)
+ return path.length; // UNC: "//server" or "\\server"
+ return p1 + 1; // UNC: "//server/" or "\\server\"
+ }
+ // DOS
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
+ var ch2 = path.charCodeAt(2);
+ if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
+ return 3; // DOS: "c:/" or "c:\"
+ if (path.length === 2)
+ return 2; // DOS: "c:" (but not "c:d")
+ }
+ // URL
+ var schemeEnd = path.indexOf(urlSchemeSeparator);
+ if (schemeEnd !== -1) {
+ var authorityStart = schemeEnd + urlSchemeSeparator.length;
+ var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
+ if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
+ // For local "file" URLs, include the leading DOS volume (if present).
+ // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
+ // special case interpreted as "the machine from which the URL is being interpreted".
+ var scheme = path.slice(0, schemeEnd);
+ var authority = path.slice(authorityStart, authorityEnd);
+ if (scheme === "file" && (authority === "" || authority === "localhost") &&
+ isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
+ var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
+ if (volumeSeparatorEnd !== -1) {
+ if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
+ // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
+ return ~(volumeSeparatorEnd + 1);
+ }
+ if (volumeSeparatorEnd === path.length) {
+ // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
+ // but not "file:///c:d" or "file:///c%3ad"
+ return ~volumeSeparatorEnd;
+ }
+ }
+ }
+ return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
+ }
+ return ~path.length; // URL: "file://server", "http://server"
+ }
+ // relative
+ return 0;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ *
+ * For example:
+ * ```ts
+ * getRootLength("a") === 0 // ""
+ * getRootLength("/") === 1 // "/"
+ * getRootLength("c:") === 2 // "c:"
+ * getRootLength("c:d") === 0 // ""
+ * getRootLength("c:/") === 3 // "c:/"
+ * getRootLength("c:\\") === 3 // "c:\\"
+ * getRootLength("//server") === 7 // "//server"
+ * getRootLength("//server/share") === 8 // "//server/"
+ * getRootLength("\\\\server") === 7 // "\\\\server"
+ * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
+ * getRootLength("file:///path") === 8 // "file:///"
+ * getRootLength("file:///c:") === 10 // "file:///c:"
+ * getRootLength("file:///c:d") === 8 // "file:///"
+ * getRootLength("file:///c:/path") === 11 // "file:///c:/"
+ * getRootLength("file://server") === 13 // "file://server"
+ * getRootLength("file://server/path") === 14 // "file://server/"
+ * getRootLength("http://server") === 13 // "http://server"
+ * getRootLength("http://server/path") === 14 // "http://server/"
+ * ```
+ */
+ function getRootLength(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength < 0 ? ~rootLength : rootLength;
+ }
+ ts.getRootLength = getRootLength;
+ // TODO(rbuckton): replace references with `resolvePath`
+ function normalizePath(path) {
+ return resolvePath(path);
+ }
+ ts.normalizePath = normalizePath;
+ function normalizePathAndParts(path) {
+ path = normalizeSlashes(path);
+ var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
+ if (parts.length) {
+ var joinedParts = root + parts.join(ts.directorySeparator);
+ return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
+ }
+ else {
+ return { path: root, parts: parts };
+ }
+ }
+ ts.normalizePathAndParts = normalizePathAndParts;
+ function getDirectoryPath(path) {
+ path = normalizeSlashes(path);
+ // If the path provided is itself the root, then return it.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return path;
+ // return the leading portion of the path up to the last (non-terminal) directory separator
+ // but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
+ }
+ ts.getDirectoryPath = getDirectoryPath;
+ function isUrl(path) {
+ return getEncodedRootLength(path) < 0;
+ }
+ ts.isUrl = isUrl;
+ function pathIsRelative(path) {
+ return /^\.\.?($|[\\/])/.test(path);
+ }
+ ts.pathIsRelative = pathIsRelative;
+ /**
+ * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
+ * like `c:`, `c:\` or `c:/`).
+ */
function isRootedDiskPath(path) {
- return path && getRootLength(path) !== 0;
+ return getEncodedRootLength(path) > 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
+ /**
+ * Determines whether a path consists only of a path root.
+ */
+ function isDiskPathRoot(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength > 0 && rootLength === path.length;
+ }
+ ts.isDiskPathRoot = isDiskPathRoot;
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
ts.convertToRelativePath = convertToRelativePath;
- function normalizedPathComponents(path, rootLength) {
- var normalizedParts = getNormalizedParts(path, rootLength);
- return [path.substr(0, rootLength)].concat(normalizedParts);
+ function pathComponents(path, rootLength) {
+ var root = path.substring(0, rootLength);
+ var rest = path.substring(rootLength).split(ts.directorySeparator);
+ if (rest.length && !lastOrUndefined(rest))
+ rest.pop();
+ return [root].concat(rest);
}
- function getNormalizedPathComponents(path, currentDirectory) {
- path = normalizeSlashes(path);
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is not normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getPathComponents(path, currentDirectory) {
+ if (currentDirectory === void 0) { currentDirectory = ""; }
+ path = combinePaths(currentDirectory, path);
var rootLength = getRootLength(path);
- if (rootLength === 0) {
- // If the path is not rooted it is relative to current directory
- path = combinePaths(normalizeSlashes(currentDirectory), path);
- rootLength = getRootLength(path);
+ return pathComponents(path, rootLength);
+ }
+ ts.getPathComponents = getPathComponents;
+ /**
+ * Reduce an array of path components to a more simplified path by navigating any
+ * `"."` or `".."` entries in the path.
+ */
+ function reducePathComponents(components) {
+ if (!some(components))
+ return [];
+ var reduced = [components[0]];
+ for (var i = 1; i < components.length; i++) {
+ var component = components[i];
+ if (!component)
+ continue;
+ if (component === ".")
+ continue;
+ if (component === "..") {
+ if (reduced.length > 1) {
+ if (reduced[reduced.length - 1] !== "..") {
+ reduced.pop();
+ continue;
+ }
+ }
+ else if (reduced[0])
+ continue;
+ }
+ reduced.push(component);
}
- return normalizedPathComponents(path, rootLength);
+ return reduced;
+ }
+ ts.reducePathComponents = reducePathComponents;
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getNormalizedPathComponents(path, currentDirectory) {
+ return reducePathComponents(getPathComponents(path, currentDirectory));
}
ts.getNormalizedPathComponents = getNormalizedPathComponents;
function getNormalizedAbsolutePath(fileName, currentDirectory) {
- return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
+ return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
- function getNormalizedPathFromPathComponents(pathComponents) {
- if (pathComponents && pathComponents.length) {
- return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator);
- }
+ /**
+ * Formats a parsed path consisting of a root component (at index 0) and zero or more path
+ * segments (at indices > 0).
+ */
+ function getPathFromPathComponents(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
+ if (pathComponents.length === 1)
+ return root;
+ return root + pathComponents.slice(1).join(ts.directorySeparator);
}
- ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents;
- function getNormalizedPathComponentsOfUrl(url) {
- // Get root length of http://www.website.com/folder1/folder2/
- // In this example the root is: http://www.website.com/
- // normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
- var urlLength = url.length;
- // Initial root length is http:// part
- var rootLength = url.indexOf("://") + "://".length;
- while (rootLength < urlLength) {
- // Consume all immediate slashes in the protocol
- // eg.initial rootlength is just file:// but it needs to consume another "/" in file:///
- if (url.charCodeAt(rootLength) === 47 /* slash */) {
- rootLength++;
- }
- else {
- // non slash character means we continue proceeding to next component of root search
+ ts.getPathFromPathComponents = getPathFromPathComponents;
+ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
+ var fromComponents = reducePathComponents(getPathComponents(from));
+ var toComponents = reducePathComponents(getPathComponents(to));
+ var start;
+ for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
+ var fromComponent = getCanonicalFileName(fromComponents[start]);
+ var toComponent = getCanonicalFileName(toComponents[start]);
+ var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
+ if (!comparer(fromComponent, toComponent))
break;
- }
}
- // there are no parts after http:// just return current string as the pathComponent
- if (rootLength === urlLength) {
- return [url];
+ if (start === 0) {
+ return toComponents;
}
- // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://)
- var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength);
- if (indexOfNextSlash !== -1) {
- // Found the "/" after the website.com so the root is length of http://www.website.com/
- // and get components after the root normally like any other folder components
- rootLength = indexOfNextSlash + 1;
- return normalizedPathComponents(url, rootLength);
- }
- else {
- // Can't find the host assume the rest of the string as component
- // but make sure we append "/" to it as root is not joined using "/"
- // eg. if url passed in was http://website.com we want to use root as [http://website.com/]
- // so that other path manipulations will be correct and it can be merged with relative paths correctly
- return [url + ts.directorySeparator];
+ var components = toComponents.slice(start);
+ var relative = [];
+ for (; start < fromComponents.length; start++) {
+ relative.push("..");
}
+ return [""].concat(relative, components);
}
- function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) {
- if (isUrl(pathOrUrl)) {
- return getNormalizedPathComponentsOfUrl(pathOrUrl);
- }
- else {
- return getNormalizedPathComponents(pathOrUrl, currentDirectory);
- }
+ function getRelativePathFromFile(from, to, getCanonicalFileName) {
+ return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
+ ts.getRelativePathFromFile = getRelativePathFromFile;
+ function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
+ Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
+ var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
+ var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
+ var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
- var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
- var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
- if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
- // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name
- // that is ["test", "cases", ""] needs to be actually ["test", "cases"]
- directoryComponents.pop();
+ var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName);
+ var firstComponent = pathComponents[0];
+ if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
+ var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
+ pathComponents[0] = prefix + firstComponent;
}
- // Find the component that differs
- var joinStartIndex;
- for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
- break;
- }
- }
- // Get the relative path
- if (joinStartIndex) {
- var relativePath = "";
- var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length);
- for (; joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (directoryComponents[joinStartIndex] !== "") {
- relativePath = relativePath + ".." + ts.directorySeparator;
- }
- }
- return relativePath + relativePathComponents.join(ts.directorySeparator);
- }
- // Cant find the relative path, get the absolute path
- var absolutePath = getNormalizedPathFromPathComponents(pathComponents);
- if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) {
- absolutePath = "file:///" + absolutePath;
- }
- return absolutePath;
+ return getPathFromPathComponents(pathComponents);
}
ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
- function getRelativePath(path, directoryPath, getCanonicalFileName) {
- var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ensurePathIsRelative(relativePath);
+ /**
+ * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
+ * with `./` or `../`) so as not to be confused with an unprefixed module name.
+ */
+ function ensurePathIsNonModuleName(path) {
+ return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path;
}
- ts.getRelativePath = getRelativePath;
- function ensurePathIsRelative(path) {
- return !pathIsRelative(path) ? "./" + path : path;
- }
- ts.ensurePathIsRelative = ensurePathIsRelative;
- function getBaseFileName(path) {
- if (path === undefined) {
- return undefined;
- }
- var i = path.lastIndexOf(ts.directorySeparator);
- return i < 0 ? path : path.substring(i + 1);
+ ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
+ function getBaseFileName(path, extensions, ignoreCase) {
+ path = normalizeSlashes(path);
+ // if the path provided is itself the root, then it has not file name.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return "";
+ // return the trailing portion of the path starting after the last (non-terminal) directory
+ // separator but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
+ var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
+ return extension ? name.slice(0, name.length - extension.length) : name;
}
ts.getBaseFileName = getBaseFileName;
- function combinePaths(path1, path2) {
- if (!(path1 && path1.length))
- return path2;
- if (!(path2 && path2.length))
- return path1;
- if (getRootLength(path2) !== 0)
- return path2;
- if (path1.charAt(path1.length - 1) === ts.directorySeparator)
- return path1 + path2;
- return path1 + ts.directorySeparator + path2;
+ /**
+ * Combines paths. If a path is absolute, it replaces any previous path.
+ */
+ function combinePaths(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ if (path)
+ path = normalizeSlashes(path);
+ for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
+ var relativePath = paths_1[_a];
+ if (!relativePath)
+ continue;
+ relativePath = normalizeSlashes(relativePath);
+ if (!path || getRootLength(relativePath) !== 0) {
+ path = relativePath;
+ }
+ else {
+ path = ensureTrailingDirectorySeparator(path) + relativePath;
+ }
+ }
+ return path;
}
ts.combinePaths = combinePaths;
+ /**
+ * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
+ * `.` and `..` path components are resolved.
+ */
+ function resolvePath(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path);
+ var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
+ return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
+ }
+ ts.resolvePath = resolvePath;
+ /**
+ * Determines whether a path has a trailing separator (`/` or `\\`).
+ */
+ function hasTrailingDirectorySeparator(path) {
+ if (path.length === 0)
+ return false;
+ var ch = path.charCodeAt(path.length - 1);
+ return ch === 47 /* slash */ || ch === 92 /* backslash */;
+ }
+ ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function removeTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) === ts.directorySeparator) {
+ if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
function ensureTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) !== ts.directorySeparator) {
+ if (!hasTrailingDirectorySeparator(path)) {
return path + ts.directorySeparator;
}
return path;
}
ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
- function comparePaths(a, b, currentDirectory, ignoreCase) {
+ function comparePathsWorker(a, b, componentComparer) {
if (a === b)
return 0 /* EqualTo */;
if (a === undefined)
return -1 /* LessThan */;
if (b === undefined)
return 1 /* GreaterThan */;
- a = removeTrailingDirectorySeparator(a);
- b = removeTrailingDirectorySeparator(b);
- var aComponents = getNormalizedPathComponents(a, currentDirectory);
- var bComponents = getNormalizedPathComponents(b, currentDirectory);
+ var aComponents = reducePathComponents(getPathComponents(a));
+ var bComponents = reducePathComponents(getPathComponents(b));
var sharedLength = Math.min(aComponents.length, bComponents.length);
- var comparer = getStringComparer(ignoreCase);
for (var i = 0; i < sharedLength; i++) {
- var result = comparer(aComponents[i], bComponents[i]);
+ var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer;
+ var result = stringComparer(aComponents[i], bComponents[i]);
if (result !== 0 /* EqualTo */) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
+ /**
+ * Performs a case-sensitive comparison of two paths.
+ */
+ function comparePathsCaseSensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseSensitive);
+ }
+ ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ /**
+ * Performs a case-insensitive comparison of two paths.
+ */
+ function comparePathsCaseInsensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseInsensitive);
+ }
+ ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
+ function comparePaths(a, b, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ a = combinePaths(currentDirectory, a);
+ b = combinePaths(currentDirectory, b);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
+ return comparePathsWorker(a, b, getStringComparer(ignoreCase));
+ }
ts.comparePaths = comparePaths;
function containsPath(parent, child, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ parent = combinePaths(currentDirectory, parent);
+ child = combinePaths(currentDirectory, child);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
if (parent === undefined || child === undefined)
return false;
if (parent === child)
return true;
- parent = removeTrailingDirectorySeparator(parent);
- child = removeTrailingDirectorySeparator(child);
- if (parent === child)
- return true;
- var parentComponents = getNormalizedPathComponents(parent, currentDirectory);
- var childComponents = getNormalizedPathComponents(child, currentDirectory);
+ var parentComponents = reducePathComponents(getPathComponents(parent));
+ var childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
- var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
+ var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (var i = 0; i < parentComponents.length; i++) {
+ var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
@@ -4050,13 +4265,17 @@ var ts;
ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
- var needAllExtensions = options && options.allowJs;
- if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
- return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ var needJsExtensions = options && options.allowJs;
+ if (!extraFileExtensions || extraFileExtensions.length === 0) {
+ return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
- return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive);
+ var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
+ return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
+ function isJavaScriptLike(scriptKind) {
+ return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
+ }
function hasJavaScriptFileExtension(fileName) {
return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}
@@ -4128,7 +4347,7 @@ var ts;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */];
+ var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
@@ -4149,9 +4368,14 @@ var ts;
}
ts.removeExtension = removeExtension;
function changeExtension(path, newExtension) {
- return (removeFileExtension(path) + newExtension);
+ return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
}
ts.changeExtension = changeExtension;
+ function changeAnyExtension(path, ext, extensions, ignoreCase) {
+ var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
+ return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
+ }
+ ts.changeAnyExtension = changeAnyExtension;
/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*/
@@ -4437,6 +4661,10 @@ var ts;
return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
}
ts.extensionIsTypeScript = extensionIsTypeScript;
+ function resolutionExtensionIsTypeScriptOrJson(ext) {
+ return extensionIsTypeScript(ext) || ext === ".json" /* Json */;
+ }
+ ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson;
/**
* Gets the extension from a path.
* Path must have a valid extension.
@@ -4457,14 +4685,34 @@ var ts;
return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); });
}
ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
- // Retrieves any string from the final "." onwards from a base file name.
- // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
- function getAnyExtensionFromPath(path) {
+ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
+ if (typeof extensions === "string")
+ extensions = [extensions];
+ for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
+ var extension = extensions_2[_i];
+ if (!startsWith(extension, "."))
+ extension = "." + extension;
+ if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
+ var pathExtension = path.slice(path.length - extension.length);
+ if (stringEqualityComparer(pathExtension, extension)) {
+ return pathExtension;
+ }
+ }
+ }
+ return "";
+ }
+ function getAnyExtensionFromPath(path, extensions, ignoreCase) {
+ // Retrieves any string from the final "." onwards from a base file name.
+ // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
+ if (extensions) {
+ return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
+ }
var baseFileName = getBaseFileName(path);
var extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
+ return "";
}
ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
@@ -4566,12 +4814,12 @@ var ts;
/* @internal */
ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
function createPollingIntervalBasedLevels(levels) {
+ var _a;
return _a = {},
_a[PollingInterval.Low] = levels.Low,
_a[PollingInterval.Medium] = levels.Medium,
_a[PollingInterval.High] = levels.High,
_a;
- var _a;
}
var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
@@ -4936,6 +5184,7 @@ var ts;
readDirectory: readDirectory,
getModifiedTime: getModifiedTime,
createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
global.gc();
@@ -5374,6 +5623,11 @@ var ts;
hash.update(data);
return hash.digest("hex");
}
+ function createSHA256Hash(data) {
+ var hash = _crypto.createHash("sha256");
+ hash.update(data);
+ return hash.digest("hex");
+ }
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -5685,7 +5939,7 @@ var ts;
Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
- Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."),
+ Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
@@ -6162,6 +6416,7 @@ var ts;
Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
+ Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
@@ -6345,6 +6600,17 @@ var ts;
Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
_0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
+ Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
+ All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
+ Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
+ Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
+ Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
+ Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
+ Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
+ Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
+ File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
+ Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
+ Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
@@ -6443,6 +6709,7 @@ var ts;
Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
+ Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
@@ -6506,6 +6773,12 @@ var ts;
Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
+ Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
+ Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
+ Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
+ Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
+ Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
+ Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -8256,11 +8529,10 @@ var ts;
}
}
function scanJSDocToken() {
+ startPos = tokenPos = pos;
if (pos >= end) {
return token = 1 /* EndOfFileToken */;
}
- startPos = pos;
- tokenPos = pos;
var ch = text.charCodeAt(pos);
pos++;
switch (ch) {
@@ -8666,7 +8938,7 @@ var ts;
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 294 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 298 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8868,12 +9140,12 @@ var ts;
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 154 /* Constructor */:
@@ -8881,6 +9153,9 @@ var ts;
case 156 /* SetAccessor */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 287 /* JSDocSignature */:
return true;
default:
ts.assertTypeIsNever(node);
@@ -8903,6 +9178,12 @@ var ts;
case 243 /* ImportDeclaration */:
case 242 /* ImportEqualsDeclaration */:
case 213 /* VariableStatement */:
+ case 234 /* ClassDeclaration */:
+ case 233 /* FunctionDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 237 /* EnumDeclaration */:
return true;
default:
return false;
@@ -8916,13 +9197,7 @@ var ts;
// Gets the nearest enclosing block scope container that has the provided node
// as a descendant, that is not the provided node.
function getEnclosingBlockScopeContainer(node) {
- var current = node.parent;
- while (current) {
- if (isBlockScope(current, current.parent)) {
- return current;
- }
- current = current.parent;
- }
+ return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
}
ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
// Return display name of an identifier
@@ -9040,6 +9315,8 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 236 /* TypeAliasDeclaration */:
+ case 151 /* PropertyDeclaration */:
+ case 150 /* PropertySignature */:
errorNode = node.name;
break;
case 192 /* ArrowFunction */:
@@ -9070,6 +9347,10 @@ var ts;
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
+ function isJsonSourceFile(file) {
+ return file.scriptKind === 6 /* JSON */;
+ }
+ ts.isJsonSourceFile = isJsonSourceFile;
function isConstEnumDeclaration(node) {
return node.kind === 237 /* EnumDeclaration */ && isConst(node);
}
@@ -9409,6 +9690,23 @@ var ts;
});
}
ts.getPropertyAssignment = getPropertyAssignment;
+ function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
+ if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
+ var expression = tsConfigSourceFile.statements[0].expression;
+ return ts.isObjectLiteralExpression(expression) && expression;
+ }
+ }
+ ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
+ function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
+ var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
+ return jsonObjectLiteral &&
+ ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
function getContainingFunction(node) {
return ts.findAncestor(node.parent, ts.isFunctionLike);
}
@@ -9786,6 +10084,10 @@ var ts;
return node && !!(node.flags & 65536 /* JavaScriptFile */);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isInJsonFile(node) {
+ return node && !!(node.flags & 16777216 /* JsonFile */);
+ }
+ ts.isInJsonFile = isInJsonFile;
function isInJSDoc(node) {
return node && !!(node.flags & 2097152 /* JSDoc */);
}
@@ -10010,6 +10312,10 @@ var ts;
}
ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
function importFromModuleSpecifier(node) {
+ return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
+ }
+ ts.importFromModuleSpecifier = importFromModuleSpecifier;
+ function tryGetImportFromModuleSpecifier(node) {
switch (node.parent.kind) {
case 243 /* ImportDeclaration */:
case 249 /* ExportDeclaration */:
@@ -10019,12 +10325,13 @@ var ts;
case 186 /* CallExpression */:
return node.parent;
case 177 /* LiteralType */:
- return ts.cast(node.parent.parent, ts.isImportTypeNode);
+ ts.Debug.assert(ts.isStringLiteral(node));
+ return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
default:
- return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
+ return undefined;
}
}
- ts.importFromModuleSpecifier = importFromModuleSpecifier;
+ ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
function getExternalModuleName(node) {
switch (node.kind) {
case 243 /* ImportDeclaration */:
@@ -10073,12 +10380,20 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 281 /* JSDocFunctionType */ &&
+ return node.kind === 283 /* JSDocFunctionType */ &&
node.parameters.length > 0 &&
node.parameters[0].name &&
node.parameters[0].name.escapedText === "new";
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
+ function isJSDocTypeAlias(node) {
+ return node.kind === 296 /* JSDocTypedefTag */ || node.kind === 291 /* JSDocCallbackTag */;
+ }
+ ts.isJSDocTypeAlias = isJSDocTypeAlias;
+ function isTypeAlias(node) {
+ return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
+ }
+ ts.isTypeAlias = isTypeAlias;
function getSourceOfAssignment(node) {
return ts.isExpressionStatement(node) &&
node.expression && ts.isBinaryExpression(node.expression) &&
@@ -10100,6 +10415,8 @@ var ts;
return v && v.initializer;
case 151 /* PropertyDeclaration */:
return node.initializer;
+ case 269 /* PropertyAssignment */:
+ return node.initializer;
}
}
function getSingleVariableOfVariableStatement(node) {
@@ -10113,9 +10430,9 @@ var ts;
node.body.kind === 238 /* ModuleDeclaration */ &&
node.body;
}
- function getJSDocCommentsAndTags(node) {
+ function getJSDocCommentsAndTags(hostNode) {
var result;
- getJSDocCommentsAndTagsWorker(node);
+ getJSDocCommentsAndTagsWorker(hostNode);
return result || ts.emptyArray;
function getJSDocCommentsAndTagsWorker(node) {
var parent = node.parent;
@@ -10130,8 +10447,7 @@ var ts;
// * @returns {number}
// */
// var x = function(name) { return name.length; }
- if (parent.parent &&
- (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) {
+ if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) {
getJSDocCommentsAndTagsWorker(parent.parent);
}
if (parent.parent && parent.parent.parent &&
@@ -10140,8 +10456,8 @@ var ts;
getSourceOfDefaultedAssignment(parent.parent.parent))) {
getJSDocCommentsAndTagsWorker(parent.parent.parent);
}
- if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ ||
- ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 /* None */ ||
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */ ||
+ ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */ ||
node.kind === 184 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 215 /* ExpressionStatement */) {
getJSDocCommentsAndTagsWorker(parent);
}
@@ -10149,7 +10465,7 @@ var ts;
if (node.kind === 148 /* Parameter */) {
result = ts.addRange(result, ts.getJSDocParameterTags(node));
}
- if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) {
+ if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) {
result = ts.addRange(result, node.initializer.jsDoc);
}
if (ts.hasJSDocNodes(node)) {
@@ -10176,7 +10492,10 @@ var ts;
}
ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
function getHostSignatureFromJSDoc(node) {
- var host = getJSDocHost(node);
+ return getHostSignatureFromJSDocHost(getJSDocHost(node));
+ }
+ ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
+ function getHostSignatureFromJSDocHost(host) {
var decl = getSourceOfDefaultedAssignment(host) ||
getSourceOfAssignment(host) ||
getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
@@ -10185,19 +10504,9 @@ var ts;
host;
return decl && ts.isFunctionLike(decl) ? decl : undefined;
}
- ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
+ ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
- while (node.parent.kind === 284 /* JSDocTypeLiteral */) {
- if (node.parent.parent.kind === 292 /* JSDocTypedefTag */) {
- node = node.parent.parent;
- }
- else {
- // node.parent.parent is a type expression, child of a parameter type
- node = node.parent.parent.parent;
- }
- }
- ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */);
- return node.parent.parent;
+ return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -10212,7 +10521,8 @@ var ts;
}
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
- return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282 /* JSDocVariadicType */;
+ var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
+ return node.dotDotDotToken !== undefined || type && type.kind === 284 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10354,8 +10664,14 @@ var ts;
if (ts.isDeclaration(name.parent)) {
return name.parent.name === name;
}
- var binExp = name.parent.parent;
- return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ else if (ts.isQualifiedName(name.parent)) {
+ var tag = name.parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === name.parent;
+ }
+ else {
+ var binExp = name.parent.parent;
+ return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ }
default:
return false;
}
@@ -10735,7 +11051,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
return 0;
case 203 /* SpreadElement */:
return 1;
@@ -11064,8 +11380,8 @@ var ts;
};
}
ts.createTextWriter = createTextWriter;
- function getResolvedExternalModuleName(host, file) {
- return file.moduleName || getExternalModuleNameFromPath(host, file.fileName);
+ function getResolvedExternalModuleName(host, file, referenceFile) {
+ return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
}
ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
@@ -11079,12 +11395,13 @@ var ts;
/**
* Resolves a local path to a path which is absolute to the base of the emit
*/
- function getExternalModuleNameFromPath(host, fileName) {
+ function getExternalModuleNameFromPath(host, fileName, referencePath) {
var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
- var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
+ var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ts.removeFileExtension(relativePath);
+ var extensionless = ts.removeFileExtension(relativePath);
+ return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
}
ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
@@ -11178,7 +11495,8 @@ var ts;
}
ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
function getThisParameter(signature) {
- if (signature.parameters.length) {
+ // callback tags do not currently support this parameters
+ if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
var thisParameter = signature.parameters[0];
if (parameterIsThisKeyword(thisParameter)) {
return thisParameter;
@@ -11263,6 +11581,9 @@ var ts;
* JavaScript file, gets the return type annotation from JSDoc.
*/
function getEffectiveReturnTypeNode(node) {
+ if (ts.isJSDocSignature(node)) {
+ return node.type && node.type.typeExpression && node.type.typeExpression.type;
+ }
return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined);
}
ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
@@ -11271,12 +11592,27 @@ var ts;
* JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
*/
function getEffectiveTypeParameterDeclarations(node) {
- return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined);
+ if (ts.isJSDocSignature(node)) {
+ return ts.emptyArray;
+ }
+ if (isJSDocTypeAlias(node)) {
+ ts.Debug.assert(node.parent.kind === 285 /* JSDocComment */);
+ var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; });
+ var templateTagNodes = templateTags;
+ templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos;
+ templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end;
+ templateTagNodes.hasTrailingComma = false;
+ return templateTagNodes;
+ }
+ return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray);
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
- var templateTag = ts.getJSDocTemplateTag(node);
- return templateTag && templateTag.typeParameters;
+ // template tags are only available when a typedef isn't already using them
+ var tag = ts.find(ts.getJSDocTags(node), function (tag) {
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ });
+ return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/**
@@ -12664,8 +13000,8 @@ var ts;
break;
case 71 /* Identifier */:
return declaration;
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */: {
+ case 297 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 145 /* QualifiedName */) {
return name.right;
@@ -12684,7 +13020,9 @@ var ts;
return undefined;
}
}
- case 292 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ return declaration.name;
+ case 296 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 248 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -12817,7 +13155,9 @@ var ts;
var tags = node.jsDocCache;
// If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
if (tags === undefined) {
- node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; });
+ var comments = ts.getJSDocCommentsAndTags(node);
+ ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
+ node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
}
return tags;
}
@@ -12935,6 +13275,11 @@ var ts;
return node.kind === 159 /* IndexSignature */;
}
ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ /* @internal */
+ function isGetOrSetAccessorDeclaration(node) {
+ return node.kind === 156 /* SetAccessor */ || node.kind === 155 /* GetAccessor */;
+ }
+ ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
// Type
function isTypePredicateNode(node) {
return node.kind === 160 /* TypePredicate */;
@@ -13063,7 +13408,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 296 /* PartiallyEmittedExpression */) {
+ while (node.kind === 300 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13419,81 +13764,89 @@ var ts;
ts.isBundle = isBundle;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 275 /* JSDocTypeExpression */;
+ return node.kind === 277 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 276 /* JSDocAllType */;
+ return node.kind === 278 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 277 /* JSDocUnknownType */;
+ return node.kind === 279 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 278 /* JSDocNullableType */;
+ return node.kind === 280 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 279 /* JSDocNonNullableType */;
+ return node.kind === 281 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 280 /* JSDocOptionalType */;
+ return node.kind === 282 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 281 /* JSDocFunctionType */;
+ return node.kind === 283 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 282 /* JSDocVariadicType */;
+ return node.kind === 284 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 283 /* JSDocComment */;
+ return node.kind === 285 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 286 /* JSDocAugmentsTag */;
+ return node.kind === 289 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 287 /* JSDocClassTag */;
+ return node.kind === 290 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocParameterTag(node) {
- return node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 292 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 289 /* JSDocReturnTag */;
+ return node.kind === 293 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 290 /* JSDocTypeTag */;
+ return node.kind === 294 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 291 /* JSDocTemplateTag */;
+ return node.kind === 295 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 292 /* JSDocTypedefTag */;
+ return node.kind === 296 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */;
+ return node.kind === 297 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */ || node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 297 /* JSDocPropertyTag */ || node.kind === 292 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 284 /* JSDocTypeLiteral */;
+ return node.kind === 286 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
+ function isJSDocCallbackTag(node) {
+ return node.kind === 291 /* JSDocCallbackTag */;
+ }
+ ts.isJSDocCallbackTag = isJSDocCallbackTag;
+ function isJSDocSignature(node) {
+ return node.kind === 287 /* JSDocSignature */;
+ }
+ ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
// Node tests
//
@@ -13502,7 +13855,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 294 /* SyntaxList */;
+ return n.kind === 298 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -13647,10 +14000,11 @@ var ts;
switch (kind) {
case 152 /* MethodSignature */:
case 157 /* CallSignature */:
+ case 287 /* JSDocSignature */:
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 163 /* ConstructorType */:
return true;
default:
@@ -13734,13 +14088,13 @@ var ts;
|| kind === 95 /* NullKeyword */
|| kind === 131 /* NeverKeyword */
|| kind === 206 /* ExpressionWithTypeArguments */
- || kind === 276 /* JSDocAllType */
- || kind === 277 /* JSDocUnknownType */
- || kind === 278 /* JSDocNullableType */
- || kind === 279 /* JSDocNonNullableType */
- || kind === 280 /* JSDocOptionalType */
- || kind === 281 /* JSDocFunctionType */
- || kind === 282 /* JSDocVariadicType */;
+ || kind === 278 /* JSDocAllType */
+ || kind === 279 /* JSDocUnknownType */
+ || kind === 280 /* JSDocNullableType */
+ || kind === 281 /* JSDocNonNullableType */
+ || kind === 282 /* JSDocOptionalType */
+ || kind === 283 /* JSDocFunctionType */
+ || kind === 284 /* JSDocVariadicType */;
}
/**
* Node test that determines whether a node is a valid type node.
@@ -13962,8 +14316,8 @@ var ts;
case 203 /* SpreadElement */:
case 207 /* AsExpression */:
case 205 /* OmittedExpression */:
- case 297 /* CommaListExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 301 /* CommaListExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -13977,12 +14331,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 296 /* PartiallyEmittedExpression */;
+ return node.kind === 300 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 295 /* NotEmittedStatement */;
+ return node.kind === 299 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14093,7 +14447,9 @@ var ts;
|| kind === 236 /* TypeAliasDeclaration */
|| kind === 147 /* TypeParameter */
|| kind === 231 /* VariableDeclaration */
- || kind === 292 /* JSDocTypedefTag */;
+ || kind === 296 /* JSDocTypedefTag */
+ || kind === 291 /* JSDocCallbackTag */
+ || kind === 297 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 233 /* FunctionDeclaration */
@@ -14128,14 +14484,14 @@ var ts;
|| kind === 213 /* VariableStatement */
|| kind === 218 /* WhileStatement */
|| kind === 225 /* WithStatement */
- || kind === 295 /* NotEmittedStatement */
- || kind === 299 /* EndOfDeclarationMarker */
- || kind === 298 /* MergeDeclarationMarker */;
+ || kind === 299 /* NotEmittedStatement */
+ || kind === 303 /* EndOfDeclarationMarker */
+ || kind === 302 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 147 /* TypeParameter */) {
- return node.parent.kind !== 291 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
+ return node.parent.kind !== 295 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14230,18 +14586,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 275 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */;
+ return node.kind >= 277 /* FirstJSDocNode */ && node.kind <= 297 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 283 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
+ return node.kind === 285 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 285 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */;
+ return node.kind >= 288 /* FirstJSDocTagNode */ && node.kind <= 297 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14292,12 +14648,12 @@ var ts;
case 231 /* VariableDeclaration */:
case 233 /* FunctionDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 275 /* JSDocTypeExpression */:
- case 278 /* JSDocNullableType */:
- case 279 /* JSDocNonNullableType */:
- case 280 /* JSDocOptionalType */:
- case 281 /* JSDocFunctionType */:
- case 282 /* JSDocVariadicType */:
+ case 277 /* JSDocTypeExpression */:
+ case 280 /* JSDocNullableType */:
+ case 281 /* JSDocNonNullableType */:
+ case 282 /* JSDocOptionalType */:
+ case 283 /* JSDocFunctionType */:
+ case 284 /* JSDocVariadicType */:
return true;
}
return false;
@@ -14787,7 +15143,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 252 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 254 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -14814,23 +15170,23 @@ var ts;
visitNode(cbNode, node.expression);
case 257 /* JsxClosingElement */:
return visitNode(cbNode, node.tagName);
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return visitNode(cbNode, node.type);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return visitNode(cbNode, node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return visitNode(cbNode, node.type);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return visitNode(cbNode, node.type);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 283 /* JSDocComment */:
+ case 285 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
+ case 297 /* JSDocPropertyTag */:
if (node.isNameFirst) {
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression);
@@ -14839,17 +15195,17 @@ var ts;
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
}
- case 289 /* JSDocReturnTag */:
+ case 293 /* JSDocReturnTag */:
return visitNode(cbNode, node.typeExpression);
- case 290 /* JSDocTypeTag */:
+ case 294 /* JSDocTypeTag */:
return visitNode(cbNode, node.typeExpression);
- case 286 /* JSDocAugmentsTag */:
+ case 289 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.class);
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
return visitNodes(cbNode, cbNodes, node.typeParameters);
- case 292 /* JSDocTypedefTag */:
+ case 296 /* JSDocTypedefTag */:
if (node.typeExpression &&
- node.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ node.typeExpression.kind === 277 /* JSDocTypeExpression */) {
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName);
}
@@ -14857,7 +15213,16 @@ var ts;
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
}
- case 284 /* JSDocTypeLiteral */:
+ case 291 /* JSDocCallbackTag */:
+ return visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression);
+ case 287 /* JSDocSignature */:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters) ||
+ visitNodes(cbNode, cbNodes, node.parameters) ||
+ visitNode(cbNode, node.type);
+ case 286 /* JSDocTypeLiteral */:
if (node.jsDocPropertyTags) {
for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
var tag = _a[_i];
@@ -14865,7 +15230,7 @@ var ts;
}
}
return;
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -14873,7 +15238,13 @@ var ts;
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
- var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ var result;
+ if (languageVersion === 100 /* JSON */) {
+ result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
+ }
+ else {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ }
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
return result;
@@ -15033,6 +15404,13 @@ var ts;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
scriptKind = ts.ensureScriptKind(fileName, scriptKind);
+ if (scriptKind === 6 /* JSON */) {
+ var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
+ ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ result_1.typeReferenceDirectives = ts.emptyArray;
+ result_1.amdDependencies = ts.emptyArray;
+ return result_1;
+ }
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
clearState();
@@ -15050,25 +15428,57 @@ var ts;
return isInvalid ? entityName : undefined;
}
Parser.parseIsolatedEntityName = parseIsolatedEntityName;
- function parseJsonText(fileName, sourceText) {
- initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */);
+ function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
+ if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
+ initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
// Set source file so that errors will be reported with this file name
sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
- var result = sourceFile;
// Prime the scanner.
nextToken();
+ var pos = getNodePos();
if (token() === 1 /* EndOfFileToken */) {
+ sourceFile.statements = createNodeArray([], pos, pos);
sourceFile.endOfFileToken = parseTokenNode();
}
- else if (token() === 17 /* OpenBraceToken */ ||
- lookAhead(function () { return token() === 9 /* StringLiteral */; })) {
- result.jsonObject = parseObjectLiteralExpression();
+ else {
+ var statement = createNode(215 /* ExpressionStatement */);
+ switch (token()) {
+ case 21 /* OpenBracketToken */:
+ statement.expression = parseArrayLiteralExpression();
+ break;
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ statement.expression = parseTokenNode();
+ break;
+ case 38 /* MinusToken */:
+ if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parsePrefixUnaryExpression();
+ }
+ else {
+ statement.expression = parseObjectLiteralExpression();
+ }
+ break;
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parseLiteralNode();
+ break;
+ }
+ // falls through
+ default:
+ statement.expression = parseObjectLiteralExpression();
+ break;
+ }
+ finishNode(statement);
+ sourceFile.statements = createNodeArray([statement], pos);
sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
}
- else {
- parseExpected(17 /* OpenBraceToken */);
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
}
sourceFile.parseDiagnostics = parseDiagnostics;
+ var result = sourceFile;
clearState();
return result;
}
@@ -15092,9 +15502,11 @@ var ts;
switch (scriptKind) {
case 1 /* JS */:
case 2 /* JSX */:
- case 6 /* JSON */:
contextFlags = 65536 /* JavaScriptFile */;
break;
+ case 6 /* JSON */:
+ contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */;
+ break;
default:
contextFlags = 0 /* None */;
break;
@@ -16340,9 +16752,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(276 /* JSDocAllType */);
+ var result = createNode(278 /* JSDocAllType */);
if (postFixEquals) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, result);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -16350,7 +16762,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(279 /* JSDocNonNullableType */);
+ var result = createNode(281 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -16374,18 +16786,18 @@ var ts;
token() === 29 /* GreaterThanToken */ ||
token() === 58 /* EqualsToken */ ||
token() === 49 /* BarToken */) {
- var result = createNode(277 /* JSDocUnknownType */, pos);
+ var result = createNode(279 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(278 /* JSDocNullableType */, pos);
+ var result = createNode(280 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(281 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(283 /* JSDocFunctionType */);
nextToken();
fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -16407,12 +16819,12 @@ var ts;
var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */);
var type = parseType();
if (dotdotdot) {
- var variadic = createNode(282 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(284 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 58 /* EqualsToken */) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, type);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, type);
}
return type;
}
@@ -16496,15 +16908,19 @@ var ts;
node.initializer = parseInitializer();
return finishNode(node);
}
+ /**
+ * @returns If return type parsing succeeds
+ */
function fillSignature(returnToken, flags, signature) {
if (!(flags & 32 /* JSDoc */)) {
signature.typeParameters = parseTypeParameters();
}
signature.parameters = parseParameterList(flags);
- signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */));
- }
- function parseReturnType(returnToken, isType) {
- return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined;
+ if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
+ signature.type = parseTypeOrTypePredicate();
+ return signature.type !== undefined;
+ }
+ return true;
}
function shouldParseReturnType(returnToken, isType) {
if (returnToken === 36 /* EqualsGreaterThanToken */) {
@@ -16783,6 +17199,9 @@ var ts;
var node = createNode(172 /* ParenthesizedType */);
parseExpected(19 /* OpenParenToken */);
node.type = parseType();
+ if (!node.type) {
+ return undefined;
+ }
parseExpected(20 /* CloseParenToken */);
return finishNode(node);
}
@@ -16791,7 +17210,12 @@ var ts;
if (kind === 163 /* ConstructorType */) {
parseExpected(94 /* NewKeyword */);
}
- fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node);
+ if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) {
+ return undefined;
+ }
+ if (!node.parameters) {
+ return undefined;
+ }
return finishNode(node);
}
function parseKeywordAndNoDot() {
@@ -16947,14 +17371,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 51 /* ExclamationToken */:
- type = createJSDocPostfixType(279 /* JSDocNonNullableType */, type);
+ type = createJSDocPostfixType(281 /* JSDocNonNullableType */, type);
break;
case 55 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createJSDocPostfixType(278 /* JSDocNullableType */, type);
+ type = createJSDocPostfixType(280 /* JSDocNullableType */, type);
break;
case 21 /* OpenBracketToken */:
parseExpected(21 /* OpenBracketToken */);
@@ -17518,7 +17942,7 @@ var ts;
// 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
if (token() === 120 /* AsyncKeyword */) {
nextToken();
- // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function
+ // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
// but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) {
return 0 /* False */;
@@ -17542,7 +17966,9 @@ var ts;
// a => (b => c)
// And think that "(b =>" was actually a parenthesized arrow function with a missing
// close paren.
- fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node);
+ if (!fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node)) {
+ return undefined;
+ }
// If we couldn't get parameters, we definitely could not parse out an arrow function.
if (!node.parameters) {
return undefined;
@@ -19905,7 +20331,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var result = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos());
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -19925,6 +20351,7 @@ var ts;
}
JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
function parseJSDocComment(parent, start, length) {
+ var _a;
var saveToken = currentToken;
var saveParseDiagnosticsLength = parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
@@ -19942,7 +20369,6 @@ var ts;
parseDiagnostics.length = saveParseDiagnosticsLength;
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
return comment;
- var _a;
}
JSDocParser.parseJSDocComment = parseJSDocComment;
var JSDocState;
@@ -19953,8 +20379,9 @@ var ts;
})(JSDocState || (JSDocState = {}));
var PropertyLikeParse;
(function (PropertyLikeParse) {
- PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property";
- PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter";
+ PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
+ PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
+ PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
})(PropertyLikeParse || (PropertyLikeParse = {}));
function parseJSDocCommentWorker(start, length) {
var content = sourceText;
@@ -20002,7 +20429,7 @@ var ts;
case 57 /* AtToken */:
if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
removeTrailingNewlines(comments);
- parseTag(indent);
+ addTag(parseTag(indent));
// NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
// Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
// for malformed examples like `/** @param {string} x @returns {number} the length */`
@@ -20076,12 +20503,29 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(283 /* JSDocComment */, start);
+ var result = createNode(285 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
}
+ function isNextNonwhitespaceTokenEndOfFile() {
+ // We must use infinite lookahead, as there could be any number of newlines :(
+ while (true) {
+ nextJSDocToken();
+ if (token() === 1 /* EndOfFileToken */) {
+ return true;
+ }
+ if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
+ return false;
+ }
+ }
+ }
function skipWhitespace() {
+ if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
+ if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
+ return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
+ }
+ }
while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
nextJSDocToken();
}
@@ -20110,8 +20554,7 @@ var ts;
case "arg":
case "argument":
case "param":
- addTag(parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */, indent));
- return;
+ return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent);
case "return":
case "returns":
tag = parseReturnTag(atToken, tagName);
@@ -20123,7 +20566,10 @@ var ts;
tag = parseTypeTag(atToken, tagName);
break;
case "typedef":
- tag = parseTypedefTag(atToken, tagName);
+ tag = parseTypedefTag(atToken, tagName, indent);
+ break;
+ case "callback":
+ tag = parseCallbackTag(atToken, tagName, indent);
break;
default:
tag = parseUnknownTag(atToken, tagName);
@@ -20137,8 +20583,11 @@ var ts;
// a badly malformed tag should not be added to the list of tags
return;
}
- tag.comment = parseTagComments(indent + tag.end - tag.pos);
- addTag(tag);
+ if (!tag.comment) {
+ // some tags, like typedef and callback, have already parsed their comments earlier
+ tag.comment = parseTagComments(indent + tag.end - tag.pos);
+ }
+ return tag;
}
function parseTagComments(indent) {
var comments = [];
@@ -20201,12 +20650,15 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(285 /* JSDocTag */, atToken.pos);
+ var result = createNode(288 /* JSDocTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
}
function addTag(tag) {
+ if (!tag) {
+ return;
+ }
if (!tags) {
tags = [tag];
tagsPos = tag.pos;
@@ -20257,9 +20709,9 @@ var ts;
if (isNameFirst) {
typeExpression = tryParseTypeExpression();
}
- var result = target === 1 /* Parameter */ ?
- createNode(288 /* JSDocParameterTag */, atToken.pos) :
- createNode(293 /* JSDocPropertyTag */, atToken.pos);
+ var result = target === 1 /* Property */ ?
+ createNode(297 /* JSDocPropertyTag */, atToken.pos) :
+ createNode(292 /* JSDocParameterTag */, atToken.pos);
var comment;
if (indent !== undefined)
comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
@@ -20279,18 +20731,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) {
- if (child.kind === 288 /* JSDocParameterTag */ || child.kind === 293 /* JSDocPropertyTag */) {
+ if (child.kind === 292 /* JSDocParameterTag */ || child.kind === 297 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 166 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -20301,27 +20753,27 @@ var ts;
}
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 293 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(289 /* JSDocReturnTag */, atToken.pos);
+ var result = createNode(293 /* JSDocReturnTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 290 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 294 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(290 /* JSDocTypeTag */, atToken.pos);
+ var result = createNode(294 /* JSDocTypeTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(atToken, tagName) {
- var result = createNode(286 /* JSDocAugmentsTag */, atToken.pos);
+ var result = createNode(289 /* JSDocAugmentsTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
@@ -20349,32 +20801,23 @@ var ts;
return node;
}
function parseClassTag(atToken, tagName) {
- var tag = createNode(287 /* JSDocClassTag */, atToken.pos);
+ var tag = createNode(290 /* JSDocClassTag */, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
}
- function parseTypedefTag(atToken, tagName) {
+ function parseTypedefTag(atToken, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(292 /* JSDocTypedefTag */, atToken.pos);
+ var typedefTag = createNode(296 /* JSDocTypedefTag */, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
- typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0);
- if (typedefTag.fullName) {
- var rightNode = typedefTag.fullName;
- while (true) {
- if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) {
- // if node is identifier - use it as name
- // otherwise use name of the rightmost part that we were able to parse
- typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name;
- break;
- }
- rightNode = rightNode.body;
- }
- }
+ typedefTag.fullName = parseJSDocTypeNameWithNamespace();
+ typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
skipWhitespace();
+ typedefTag.comment = parseTagComments(indent);
typedefTag.typeExpression = typeExpression;
+ var end;
if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
var child = void 0;
var jsdocTypeLiteral = void 0;
@@ -20382,9 +20825,9 @@ var ts;
var start_3 = scanner.getStartPos();
while (child = tryParse(function () { return parseChildPropertyTag(); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_3);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_3);
}
- if (child.kind === 290 /* JSDocTypeTag */) {
+ if (child.kind === 294 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -20403,23 +20846,68 @@ var ts;
typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
childTypeTag.typeExpression :
finishNode(jsdocTypeLiteral);
+ end = typedefTag.typeExpression.end;
}
}
- return finishNode(typedefTag);
- function parseJSDocTypeNameWithNamespace(flags) {
- var pos = scanner.getTokenPos();
- var typeNameOrNamespaceName = parseJSDocIdentifierName();
- if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) {
- var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos);
- jsDocNamespaceNode.flags |= flags;
- jsDocNamespaceNode.name = typeNameOrNamespaceName;
- jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */);
- return finishNode(jsDocNamespaceNode);
+ // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
+ return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
+ }
+ function parseJSDocTypeNameWithNamespace(nested) {
+ var pos = scanner.getTokenPos();
+ var typeNameOrNamespaceName = parseJSDocIdentifierName();
+ if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) {
+ var jsDocNamespaceNode = createNode(238 /* ModuleDeclaration */, pos);
+ if (nested) {
+ jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
}
- if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) {
- typeNameOrNamespaceName.isInJSDocNamespace = true;
+ jsDocNamespaceNode.name = typeNameOrNamespaceName;
+ jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
+ return finishNode(jsDocNamespaceNode);
+ }
+ if (typeNameOrNamespaceName && nested) {
+ typeNameOrNamespaceName.isInJSDocNamespace = true;
+ }
+ return typeNameOrNamespaceName;
+ }
+ function parseCallbackTag(atToken, tagName, indent) {
+ var callbackTag = createNode(291 /* JSDocCallbackTag */, atToken.pos);
+ callbackTag.atToken = atToken;
+ callbackTag.tagName = tagName;
+ callbackTag.fullName = parseJSDocTypeNameWithNamespace();
+ callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
+ skipWhitespace();
+ callbackTag.comment = parseTagComments(indent);
+ var child;
+ var start = scanner.getStartPos();
+ var jsdocSignature = createNode(287 /* JSDocSignature */, start);
+ jsdocSignature.parameters = [];
+ while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) {
+ jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
+ }
+ var returnTag = tryParse(function () {
+ if (token() === 57 /* AtToken */) {
+ nextJSDocToken();
+ var tag = parseTag(indent);
+ if (tag && tag.kind === 293 /* JSDocReturnTag */) {
+ return tag;
+ }
+ }
+ });
+ if (returnTag) {
+ jsdocSignature.type = returnTag;
+ }
+ callbackTag.typeExpression = finishNode(jsdocSignature);
+ return finishNode(callbackTag);
+ }
+ function getJSDocTypeAliasName(fullName) {
+ if (fullName) {
+ var rightNode = fullName;
+ while (true) {
+ if (ts.isIdentifier(rightNode) || !rightNode.body) {
+ return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
+ }
+ rightNode = rightNode.body;
}
- return typeNameOrNamespaceName;
}
}
function escapedTextsEqual(a, b) {
@@ -20435,7 +20923,7 @@ var ts;
return a.escapedText === b.escapedText;
}
function parseChildPropertyTag() {
- return parseChildParameterOrPropertyTag(0 /* Property */);
+ return parseChildParameterOrPropertyTag(1 /* Property */);
}
function parseChildParameterOrPropertyTag(target, name) {
var canParseTag = true;
@@ -20445,7 +20933,8 @@ var ts;
case 57 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target);
- if (child && child.kind === 288 /* JSDocParameterTag */ &&
+ if (child && child.kind === 292 /* JSDocParameterTag */ &&
+ target !== 4 /* CallbackParameter */ &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
}
@@ -20484,20 +20973,20 @@ var ts;
var t;
switch (tagName.escapedText) {
case "type":
- return target === 0 /* Property */ && parseTypeTag(atToken, tagName);
+ return target === 1 /* Property */ && parseTypeTag(atToken, tagName);
case "prop":
case "property":
- t = 0 /* Property */;
+ t = 1 /* Property */;
break;
case "arg":
case "argument":
case "param":
- t = 1 /* Parameter */;
+ t = 2 /* Parameter */ | 4 /* CallbackParameter */;
break;
default:
return false;
}
- if (target !== t) {
+ if (!(target & t)) {
return false;
}
var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined);
@@ -20530,7 +21019,7 @@ var ts;
break;
}
}
- var result = createNode(291 /* JSDocTemplateTag */, atToken.pos);
+ var result = createNode(295 /* JSDocTemplateTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -20579,7 +21068,7 @@ var ts;
var pos = scanner.getTokenPos();
var end = scanner.getTextPos();
var result = createNode(71 /* Identifier */, pos);
- result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end));
+ result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText());
finishNode(result, end);
nextJSDocToken();
return result;
@@ -21383,7 +21872,7 @@ var ts;
var thisParentContainer; // Container one level up
var blockScopeContainer;
var lastContainer;
- var delayedTypedefs;
+ var delayedTypeAliases;
var seenThisKeyword;
// state used by control flow analysis
var currentFlow;
@@ -21441,7 +21930,7 @@ var ts;
thisParentContainer = undefined;
blockScopeContainer = undefined;
lastContainer = undefined;
- delayedTypedefs = undefined;
+ delayedTypeAliases = undefined;
seenThisKeyword = false;
currentFlow = undefined;
currentBreakTarget = undefined;
@@ -21515,6 +22004,7 @@ var ts;
return "__constructor" /* Constructor */;
case 162 /* FunctionType */:
case 157 /* CallSignature */:
+ case 287 /* JSDocSignature */:
return "__call" /* Call */;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */:
@@ -21523,6 +22013,10 @@ var ts;
return "__index" /* Index */;
case 249 /* ExportDeclaration */:
return "__export" /* ExportStar */;
+ case 273 /* SourceFile */:
+ // json file should behave as
+ // module.exports = ...
+ return "export=" /* ExportEquals */;
case 199 /* BinaryExpression */:
if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) {
// module.exports = ...
@@ -21530,18 +22024,15 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 148 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 281 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 283 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
- case 292 /* JSDocTypedefTag */:
- var name_2 = ts.getNameOfJSDocTypedef(node);
- return typeof name_2 !== "undefined" ? name_2.escapedText : undefined;
}
}
function getDisplayName(node) {
@@ -21679,9 +22170,9 @@ var ts;
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
- if (node.kind === 292 /* JSDocTypedefTag */)
+ if (ts.isJSDocTypeAlias(node))
ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
- if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypedefTag(node)) {
+ if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
}
@@ -21846,23 +22337,6 @@ var ts;
ts.forEachChild(node, bind, bindEach);
}
function bindChildrenWorker(node) {
- // Binding of JsDocComment should be done before the current block scope container changes.
- // because the scope of JsDocComment should not be affected by whether the current node is a
- // container or not.
- if (ts.hasJSDocNodes(node)) {
- if (ts.isInJavaScriptFile(node)) {
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var j = _a[_i];
- bind(j);
- }
- }
- else {
- for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
- var j = _c[_b];
- setParentPointers(node, j);
- }
- }
- }
if (checkUnreachable(node)) {
bindEachChild(node);
return;
@@ -21928,11 +22402,9 @@ var ts;
case 186 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 283 /* JSDocComment */:
- bindJSDocComment(node);
- break;
- case 292 /* JSDocTypedefTag */:
- bindJSDocTypedefTag(node);
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
case 273 /* SourceFile */:
@@ -21947,6 +22419,7 @@ var ts;
bindEachChild(node);
break;
}
+ bindJSDoc(node);
}
function isNarrowingExpression(expr) {
switch (expr.kind) {
@@ -22548,23 +23021,10 @@ var ts;
bindInitializedVariableFlow(node);
}
}
- function bindJSDocComment(node) {
- ts.forEachChild(node, function (n) {
- if (n.kind !== 292 /* JSDocTypedefTag */) {
- bind(n);
- }
- });
- }
- function bindJSDocTypedefTag(node) {
- ts.forEachChild(node, function (n) {
- // if the node has a fullName "A.B.C", that means symbol "C" was already bound
- // when we visit "fullName"; so when we visit the name "C" as the next child of
- // the jsDocTypedefTag, we should skip binding it.
- if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) {
- return;
- }
- bind(n);
- });
+ function bindJSDocTypeAlias(node) {
+ if (node.fullName) {
+ setParentPointers(node, node.fullName);
+ }
}
function bindCallExpressionFlow(node) {
// If the target of the call expression is a function expression or arrow function we have
@@ -22596,7 +23056,7 @@ var ts;
case 237 /* EnumDeclaration */:
case 183 /* ObjectLiteralExpression */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 262 /* JsxAttributes */:
return 1 /* IsContainer */;
case 235 /* InterfaceDeclaration */:
@@ -22618,7 +23078,8 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 157 /* CallSignature */:
- case 281 /* JSDocFunctionType */:
+ case 287 /* JSDocSignature */:
+ case 283 /* JSDocFunctionType */:
case 162 /* FunctionType */:
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
@@ -22680,7 +23141,7 @@ var ts;
case 237 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 183 /* ObjectLiteralExpression */:
case 235 /* InterfaceDeclaration */:
case 262 /* JsxAttributes */:
@@ -22694,6 +23155,7 @@ var ts;
case 163 /* ConstructorType */:
case 157 /* CallSignature */:
case 158 /* ConstructSignature */:
+ case 287 /* JSDocSignature */:
case 159 /* IndexSignature */:
case 153 /* MethodDeclaration */:
case 152 /* MethodSignature */:
@@ -22703,7 +23165,9 @@ var ts;
case 233 /* FunctionDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
case 236 /* TypeAliasDeclaration */:
case 176 /* MappedType */:
// All the children of these container types are never visible through another
@@ -22878,22 +23342,35 @@ var ts;
bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */);
}
function delayedBindJSDocTypedefTag() {
- if (!delayedTypedefs) {
+ if (!delayedTypeAliases) {
return;
}
var saveContainer = container;
var saveLastContainer = lastContainer;
var saveBlockScopeContainer = blockScopeContainer;
var saveParent = parent;
- for (var _i = 0, delayedTypedefs_1 = delayedTypedefs; _i < delayedTypedefs_1.length; _i++) {
- var delay = delayedTypedefs_1[_i];
- (container = delay.container, lastContainer = delay.lastContainer, blockScopeContainer = delay.blockScopeContainer, parent = delay.parent);
- bindBlockScopedDeclaration(delay.typedef, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
+ var saveCurrentFlow = currentFlow;
+ for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
+ var typeAlias = delayedTypeAliases_1[_i];
+ var host = ts.getJSDocHost(typeAlias);
+ container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
+ blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
+ currentFlow = { flags: 2 /* Start */ };
+ parent = typeAlias;
+ bind(typeAlias.typeExpression);
+ if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) {
+ parent = typeAlias.parent;
+ bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
+ }
+ else {
+ bind(typeAlias.fullName);
+ }
}
container = saveContainer;
lastContainer = saveLastContainer;
blockScopeContainer = saveBlockScopeContainer;
parent = saveParent;
+ currentFlow = saveCurrentFlow;
}
// The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
// check for reserved words used as identifiers in strict mode code.
@@ -23045,8 +23522,6 @@ var ts;
// Here the current node is "foo", which is a container, but the scope of "MyType" should
// not be inside "foo". Therefore we always bind @typedef before bind the parent node,
// and skip binding this tag later when binding all the other jsdoc tags.
- if (ts.isInJavaScriptFile(node))
- bindJSDocTypedefTagIfAny(node);
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
// destination symbol tables are:
@@ -23077,25 +23552,22 @@ var ts;
}
else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
+ bindJSDoc(node);
}
inStrictMode = saveInStrictMode;
}
- function bindJSDocTypedefTagIfAny(node) {
- if (!ts.hasJSDocNodes(node)) {
- return;
- }
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var jsDoc = _a[_i];
- if (!jsDoc.tags) {
- continue;
+ function bindJSDoc(node) {
+ if (ts.hasJSDocNodes(node)) {
+ if (ts.isInJavaScriptFile(node)) {
+ for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
+ var j = _a[_i];
+ bind(j);
+ }
}
- for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) {
- var tag = _c[_b];
- if (tag.kind === 292 /* JSDocTypedefTag */) {
- var savedParent = parent;
- parent = jsDoc;
- bind(tag);
- parent = savedParent;
+ else {
+ for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
+ var j = _c[_b];
+ setParentPointers(node, j);
}
}
}
@@ -23130,7 +23602,7 @@ var ts;
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if (node.isInJSDocNamespace) {
var parentNode = node.parent;
- while (parentNode && parentNode.kind !== 292 /* JSDocTypedefTag */) {
+ while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
parentNode = parentNode.parent;
}
bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
@@ -23232,11 +23704,12 @@ var ts;
case 156 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */);
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
+ case 287 /* JSDocSignature */:
case 163 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 176 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 183 /* ObjectLiteralExpression */:
@@ -23292,24 +23765,23 @@ var ts;
// falls through
case 239 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 288 /* JSDocParameterTag */:
- if (node.parent.kind !== 284 /* JSDocTypeLiteral */) {
+ case 292 /* JSDocParameterTag */:
+ if (node.parent.kind === 287 /* JSDocSignature */) {
+ return bindParameter(node);
+ }
+ if (node.parent.kind !== 286 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 293 /* JSDocPropertyTag */:
+ case 297 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 292 /* JSDocTypedefTag */: {
- var fullName = node.fullName;
- if (!fullName || fullName.kind === 71 /* Identifier */) {
- (delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent });
- }
- break;
- }
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
function bindPropertyWorker(node) {
@@ -23323,6 +23795,13 @@ var ts;
if (ts.isExternalModule(file)) {
bindSourceFileAsExternalModule();
}
+ else if (ts.isJsonSourceFile(file)) {
+ bindSourceFileAsExternalModule();
+ // Create symbol equivalent for the module.exports = {}
+ var originalSymbol = file.symbol;
+ declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
+ file.symbol = originalSymbol;
+ }
}
function bindSourceFileAsExternalModule() {
bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
@@ -23662,6 +24141,9 @@ var ts;
}
}
function bindParameter(node) {
+ if (node.kind === 292 /* JSDocParameterTag */ && container.kind !== 287 /* JSDocSignature */) {
+ return;
+ }
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
@@ -23720,24 +24202,30 @@ var ts;
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
function getInferTypeContainer(node) {
- while (node) {
- var parent_2 = node.parent;
- if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) {
- return parent_2;
- }
- node = parent_2;
- }
- return undefined;
+ var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
+ return extendsType && extendsType.parent;
}
function bindTypeParameter(node) {
- if (node.parent.kind === 171 /* InferType */) {
- var container_1 = getInferTypeContainer(node.parent);
+ if (ts.isJSDocTemplateTag(node.parent)) {
+ var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent);
if (container_1) {
if (!container_1.locals) {
container_1.locals = ts.createSymbolTable();
}
declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
}
+ else {
+ declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ }
+ }
+ else if (node.parent.kind === 171 /* InferType */) {
+ var container_2 = getInferTypeContainer(node.parent);
+ if (container_2) {
+ if (!container_2.locals) {
+ container_2.locals = ts.createSymbolTable();
+ }
+ declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */);
+ }
else {
bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node));
}
@@ -23999,7 +24487,7 @@ var ts;
else {
// A ClassDeclaration is ES6 syntax.
transformFlags = subtreeFlags | 192 /* AssertES2015 */;
- // A class with a parameter property assignment, property initializer, or decorator is
+ // A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
@@ -24136,9 +24624,9 @@ var ts;
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
- // If the PropertyDeclaration has an initializer, we need to inform its ancestor
+ // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
- if (node.initializer) {
+ if (node.initializer || ts.isComputedPropertyName(node.name)) {
transformFlags |= 8192 /* ContainsPropertyInitializer */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
@@ -24362,7 +24850,7 @@ var ts;
break;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -24634,7 +25122,7 @@ var ts;
return 940049729 /* BindingPatternExcludes */;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
case 190 /* ParenthesizedExpression */:
case 97 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -24652,7 +25140,7 @@ var ts;
*/
function setParentPointers(parent, child) {
child.parent = parent;
- ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); });
+ ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
}
})(ts || (ts = {}));
/** @internal */
@@ -24850,7 +25338,8 @@ var ts;
(function (Extensions) {
Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
- Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */
+ Extensions[Extensions["Json"] = 2] = "Json";
+ Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */
})(Extensions || (Extensions = {}));
/** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
function resolvedTypeScriptOnly(resolved) {
@@ -24894,7 +25383,13 @@ var ts;
function readJson(path, host) {
try {
var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
@@ -25425,7 +25920,11 @@ var ts;
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
- var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
+ var result = jsOnly ?
+ tryResolve(Extensions.JavaScript) :
+ (tryResolve(Extensions.TypeScript) ||
+ tryResolve(Extensions.JavaScript) ||
+ (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
if (result && result.value) {
var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations);
@@ -25480,7 +25979,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
- if (!ts.pathEndsWithDirectorySeparator(candidate)) {
+ if (!ts.hasTrailingDirectorySeparator(candidate)) {
if (!onlyRecordFailures) {
var parentOfCandidate = ts.getDirectoryPath(candidate);
if (!directoryProbablyExists(parentOfCandidate, state.host)) {
@@ -25565,6 +26064,10 @@ var ts;
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ if (extensions === Extensions.Json) {
+ var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
+ return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
+ }
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
@@ -25585,9 +26088,9 @@ var ts;
function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) {
if (!onlyRecordFailures) {
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ var directory_1 = ts.getDirectoryPath(candidate);
+ if (directory_1) {
+ onlyRecordFailures = !directoryProbablyExists(directory_1, state.host);
}
}
switch (extensions) {
@@ -25597,6 +26100,8 @@ var ts;
return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
case Extensions.JavaScript:
return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
+ case Extensions.Json:
+ return tryExtension(".json" /* Json */);
}
function tryExtension(ext) {
var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
@@ -25649,8 +26154,11 @@ var ts;
}
else {
var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state);
- if (typeof jsPath === "string") {
- subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */;
+ if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) {
+ var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1);
+ subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) {
+ return ts.tryRemoveExtension(potentialSubModule_1, extension);
+ }) || potentialSubModule_1) + ".d.ts" /* Dts */;
}
else {
subModuleName = "index.d.ts";
@@ -25683,9 +26191,18 @@ var ts;
}
}
function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) {
- var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state);
+ var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
if (!file) {
- return undefined;
+ if (extensions === Extensions.TypeScript) {
+ // When resolving typescript modules, try resolving using main field as well
+ file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state);
+ if (!file) {
+ return undefined;
+ }
+ }
+ else {
+ return undefined;
+ }
}
var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host);
var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state);
@@ -25718,6 +26235,8 @@ var ts;
switch (extensions) {
case Extensions.JavaScript:
return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
+ case Extensions.Json:
+ return extension === ".json" /* Json */;
case Extensions.TypeScript:
return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
case Extensions.DtsOnly:
@@ -25788,7 +26307,7 @@ var ts;
if (packageResult) {
return packageResult;
}
- if (extensions !== Extensions.JavaScript) {
+ if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
var nodeModulesAtTypesExists = nodeModulesFolderExists;
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
@@ -26213,7 +26732,7 @@ var ts;
checkSourceFile(file);
var diagnostics = [];
ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
- checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) {
+ checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) {
if (!unusedIsError(kind)) {
diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
}
@@ -26283,6 +26802,7 @@ var ts;
var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
+ var resolvingSignaturesArray = [resolvingSignature];
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
var globals = ts.createSymbolTable();
@@ -26327,8 +26847,6 @@ var ts;
var deferredGlobalExtractSymbol;
var deferredNodes;
var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
- var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked.
- var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice
var flowLoopStart = 0;
var flowLoopCount = 0;
var sharedFlowCount = 0;
@@ -26639,17 +27157,17 @@ var ts;
}
function getJsxNamespace(location) {
if (location) {
- var file = ts.getSourceFileOfNode(location);
- if (file) {
- if (file.localJsxNamespace) {
- return file.localJsxNamespace;
+ var file_1 = ts.getSourceFileOfNode(location);
+ if (file_1) {
+ if (file_1.localJsxNamespace) {
+ return file_1.localJsxNamespace;
}
- var jsxPragma = file.pragmas.get("jsx");
+ var jsxPragma = file_1.pragmas.get("jsx");
if (jsxPragma) {
var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
- file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
- if (file.localJsxFactory) {
- return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file_1.localJsxFactory) {
+ return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText;
}
}
}
@@ -26761,6 +27279,8 @@ var ts;
function mergeSymbol(target, source) {
if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
(source.flags | target.flags) & 67108864 /* JSContainer */) {
+ var targetValueDeclaration = target.valueDeclaration;
+ ts.Debug.assert(!!(target.flags & 33554432 /* Transient */));
// Javascript static-property-assignment declarations always merge, even though they are also values
if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
// reset flag when merging instantiated module into value module that has only const enums
@@ -26786,7 +27306,12 @@ var ts;
}
if ((source.flags | target.flags) & 67108864 /* JSContainer */) {
var sourceInitializer = ts.getJSInitializerSymbol(source);
- var targetInitializer = ts.getJSInitializerSymbol(target);
+ var init = ts.getDeclaredJavascriptInitializer(targetValueDeclaration) || ts.getAssignedJavascriptInitializer(targetValueDeclaration);
+ var targetInitializer = init && init.symbol ? init.symbol : target;
+ if (!(targetInitializer.flags & 33554432 /* Transient */)) {
+ var mergedInitializer = getMergedSymbol(targetInitializer);
+ targetInitializer = mergedInitializer === targetInitializer ? cloneSymbol(targetInitializer) : mergedInitializer;
+ }
if (sourceInitializer !== source || targetInitializer !== target) {
mergeSymbol(targetInitializer, sourceInitializer);
}
@@ -27070,7 +27595,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) {
+ if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 285 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -27269,6 +27794,12 @@ var ts;
location = location.parent;
}
break;
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ // js type aliases do not resolve names from their host, so skip past it
+ lastLocation = location;
+ location = ts.getJSDocHost(location).parent;
+ continue;
}
if (isSelfReferenceLocation(location)) {
lastSelfReferenceLocation = location;
@@ -27384,9 +27915,11 @@ var ts;
function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
- var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
- if (decl.kind === 147 /* TypeParameter */ && parent === container) {
- return true;
+ if (decl.kind === 147 /* TypeParameter */) {
+ var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
+ if (parent === container) {
+ return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias));
+ }
}
}
return false;
@@ -27597,8 +28130,8 @@ var ts;
else {
exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias);
}
- var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
+ var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias);
if (!exportDefaultSymbol && !hasSyntheticDefault) {
error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
}
@@ -27850,7 +28383,7 @@ var ts;
var symbol;
if (name.kind === 71 /* Identifier */) {
var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0;
- var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSPrototype(name, meaning) : undefined;
+ var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined;
symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true);
if (!symbol) {
return symbolFromJSPrototype;
@@ -27859,40 +28392,40 @@ var ts;
else if (name.kind === 145 /* QualifiedName */ || name.kind === 184 /* PropertyAccessExpression */) {
var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression;
var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name;
- var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
- if (!namespace || ts.nodeIsMissing(right)) {
+ var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
+ if (!namespace_1 || ts.nodeIsMissing(right)) {
return undefined;
}
- else if (namespace === unknownSymbol) {
- return namespace;
+ else if (namespace_1 === unknownSymbol) {
+ return namespace_1;
}
if (ts.isInJavaScriptFile(name)) {
- var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration);
+ var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration);
if (initializer) {
- namespace = getSymbolOfNode(initializer);
+ namespace_1 = getSymbolOfNode(initializer);
}
// Currently, IIFEs may not have a symbol and we don't know about their contents. Give up in this case.
- if (!namespace) {
+ if (!namespace_1) {
return undefined;
}
- if (namespace.valueDeclaration &&
- ts.isVariableDeclaration(namespace.valueDeclaration) &&
- namespace.valueDeclaration.initializer &&
- isCommonJsRequire(namespace.valueDeclaration.initializer)) {
- var moduleName = namespace.valueDeclaration.initializer.arguments[0];
+ if (namespace_1.valueDeclaration &&
+ ts.isVariableDeclaration(namespace_1.valueDeclaration) &&
+ namespace_1.valueDeclaration.initializer &&
+ isCommonJsRequire(namespace_1.valueDeclaration.initializer)) {
+ var moduleName = namespace_1.valueDeclaration.initializer.arguments[0];
var moduleSym = resolveExternalModuleName(moduleName, moduleName);
if (moduleSym) {
var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
if (resolvedModuleSymbol) {
- namespace = resolvedModuleSymbol;
+ namespace_1 = resolvedModuleSymbol;
}
}
}
}
- symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning);
+ symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning);
if (!symbol) {
if (!ignoreErrors) {
- error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
+ error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right));
}
return undefined;
}
@@ -27904,24 +28437,37 @@ var ts;
return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
}
/**
- * For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
+ * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
* Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
* name resolution won't work either.
+ * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
*/
- function resolveEntityNameFromJSPrototype(name, meaning) {
- if (isJSDocTypeReference(name.parent) && ts.isJSDocTag(name.parent.parent.parent)) {
- var host_1 = ts.getJSDocHost(name.parent.parent.parent);
- if (ts.isExpressionStatement(host_1) &&
- ts.isBinaryExpression(host_1.expression) &&
- ts.getSpecialPropertyAssignmentKind(host_1.expression) === 3 /* PrototypeProperty */) {
- var symbol = getSymbolOfNode(host_1.expression.left);
- if (symbol) {
- var secondaryLocation = symbol.parent.valueDeclaration;
- return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
- }
+ function resolveEntityNameFromJSSpecialAssignment(name, meaning) {
+ if (isJSDocTypeReference(name.parent)) {
+ var secondaryLocation = getJSSpecialAssignmentLocation(name.parent);
+ if (secondaryLocation) {
+ return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
}
}
}
+ function getJSSpecialAssignmentLocation(node) {
+ var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
+ if (typeAlias) {
+ return;
+ }
+ var host = ts.getJSDocHost(node);
+ if (ts.isExpressionStatement(host) &&
+ ts.isBinaryExpression(host.expression) &&
+ ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) {
+ var symbol = getSymbolOfNode(host.expression.left);
+ return symbol && symbol.parent.valueDeclaration;
+ }
+ var sig = ts.getHostSignatureFromJSDocHost(host);
+ if (sig) {
+ var symbol = getSymbolOfNode(sig);
+ return symbol && symbol.valueDeclaration;
+ }
+ }
function resolveExternalModuleName(location, moduleReferenceExpression) {
return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0);
}
@@ -27970,7 +28516,7 @@ var ts;
}
}
// May be an untyped module. If so, ignore resolutionDiagnostic.
- if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
+ if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
if (isForAugmentation) {
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
@@ -27982,7 +28528,22 @@ var ts;
return undefined;
}
if (moduleNotFoundError) {
- // report errors only if it was requested
+ // For relative paths, see if this was possibly a projectReference redirect
+ if (ts.pathIsRelative(moduleReference)) {
+ var sourceFile_1 = ts.getSourceFileOfNode(location);
+ var redirects = sourceFile_1.redirectedReferences;
+ if (redirects) {
+ var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
+ for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
+ var ext = _a[_i];
+ var probePath = normalizedTargetPath + ext;
+ if (redirects.indexOf(probePath) >= 0) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ return undefined;
+ }
+ }
+ }
+ }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -28429,7 +28990,7 @@ var ts;
* @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
*/
function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
- if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) {
+ if (symbol && enclosingDeclaration) {
var initialSymbol = symbol;
var meaningToLook = meaning;
while (symbol) {
@@ -28446,6 +29007,14 @@ var ts;
}
return hasAccessibleDeclarations;
}
+ else {
+ if (ts.some(symbol.declarations, hasExternalModuleSymbol)) {
+ // Any meaning of a module symbol is always accessible via an `import` type
+ return {
+ accessibility: 0 /* Accessible */
+ };
+ }
+ }
// If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
// It could be a qualified symbol and hence verify the path
// e.g.:
@@ -28511,6 +29080,11 @@ var ts;
isDeclarationVisible(declaration.parent.parent.parent)) {
return addVisibleAlias(declaration, declaration.parent.parent);
}
+ else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
+ && !ts.hasModifier(declaration, 1 /* Export */)
+ && isDeclarationVisible(declaration.parent)) {
+ return addVisibleAlias(declaration, declaration);
+ }
// Declaration is not visible
return false;
}
@@ -28678,7 +29252,7 @@ var ts;
flags: flags,
tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop },
encounteredError: false,
- symbolStack: undefined,
+ visitedSymbols: undefined,
inferTypeParameters: undefined
};
}
@@ -28770,16 +29344,25 @@ var ts;
}
if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
- return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol)));
+ return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
+ }
+ if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.flags & 32768 /* TypeParameter */ &&
+ ts.length(type.symbol.declarations) &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context) &&
+ !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined);
}
var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?");
// Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
}
if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
- var name = symbolToTypeReferenceName(type.aliasSymbol);
var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
- return ts.createTypeReferenceNode(name, typeArgumentNodes);
+ if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
+ return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
+ return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes);
}
if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) {
var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types;
@@ -28828,14 +29411,26 @@ var ts;
ts.Debug.assert(!!(type.flags & 65536 /* Object */));
var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
- var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type));
+ var appropriateConstraintTypeNode;
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
+ // We have a { [P in keyof T]: X }
+ // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
+ appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
+ }
+ else {
+ appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
+ }
+ var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
}
function createAnonymousTypeNode(type) {
var symbol = type.symbol;
+ var id;
if (symbol) {
+ var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
+ id = (isConstructorObject ? "+" : "") + getSymbolId(symbol);
if (isJavaScriptConstructor(symbol.valueDeclaration)) {
// Instance and static types share the same symbol; only add 'typeof' for the static side.
var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */;
@@ -28847,7 +29442,7 @@ var ts;
shouldWriteTypeOfFunctionSymbol()) {
return symbolToTypeNode(symbol, context, 67216319 /* Value */);
}
- else if (ts.contains(context.symbolStack, symbol)) {
+ else if (context.visitedSymbols && context.visitedSymbols.has(id)) {
// If type is an anonymous type literal in a type alias declaration, use type alias name
var typeAlias = getTypeAliasForTypeLiteral(type);
if (typeAlias) {
@@ -28861,19 +29456,13 @@ var ts;
else {
// Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
// of types allows us to catch circular references to instantiations of the same anonymous type
- if (!context.symbolStack) {
- context.symbolStack = [];
- }
- var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
- if (isConstructorObject) {
- return createTypeNodeFromObjectType(type);
- }
- else {
- context.symbolStack.push(symbol);
- var result = createTypeNodeFromObjectType(type);
- context.symbolStack.pop();
- return result;
+ if (!context.visitedSymbols) {
+ context.visitedSymbols = ts.createMap();
}
+ context.visitedSymbols.set(id, true);
+ var result = createTypeNodeFromObjectType(type);
+ context.visitedSymbols.delete(id);
+ return result;
}
}
else {
@@ -28890,7 +29479,7 @@ var ts;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
- return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively
+ return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively
(!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed
}
}
@@ -28922,11 +29511,6 @@ var ts;
var typeLiteralNode = ts.createTypeLiteralNode(members);
return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
}
- function symbolToTypeReferenceName(symbol) {
- // Unnamed function expressions and arrow functions have reserved names that we don't want to display
- var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("");
- return entityName;
- }
function typeReferenceToTypeNode(type) {
var typeArguments = type.typeArguments || ts.emptyArray;
if (type.target === globalArrayType) {
@@ -28959,7 +29543,7 @@ var ts;
else {
var outerTypeParameters = type.target.outerTypeParameters;
var i = 0;
- var qualifiedName = void 0;
+ var resultType = void 0;
if (outerTypeParameters) {
var length_1 = outerTypeParameters.length;
while (i < length_1) {
@@ -28973,55 +29557,65 @@ var ts;
// the default outer type arguments), we don't show the group.
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
- var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice);
- var namePart = symbolToTypeReferenceName(parent);
- (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1;
- if (qualifiedName) {
- ts.Debug.assert(!qualifiedName.right);
- qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart);
- qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined);
- }
- else {
- qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined);
- }
+ var flags_2 = context.flags;
+ context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
+ var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice);
+ context.flags = flags_2;
+ resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
}
}
}
- var entityName = void 0;
- var nameIdentifier = symbolToTypeReferenceName(type.symbol);
- if (qualifiedName) {
- ts.Debug.assert(!qualifiedName.right);
- qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier);
- entityName = qualifiedName;
- }
- else {
- entityName = nameIdentifier;
- }
var typeArgumentNodes = void 0;
if (typeArguments.length > 0) {
var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
}
- if (typeArgumentNodes) {
- var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right;
- lastIdentifier.typeArguments = undefined;
- }
- return ts.createTypeReferenceNode(entityName, typeArgumentNodes);
+ var flags = context.flags;
+ context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
+ var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes);
+ context.flags = flags;
+ return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
}
}
- function addToQualifiedNameMissingRightIdentifier(left, right) {
- ts.Debug.assert(left.right === undefined);
- if (right.kind === 71 /* Identifier */) {
- left.right = right;
- return left;
+ function appendReferenceToType(root, ref) {
+ if (ts.isImportTypeNode(root)) {
+ // first shift type arguments
+ var innerParams = root.typeArguments;
+ if (root.qualifier) {
+ (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
+ }
+ root.typeArguments = ref.typeArguments;
+ // then move qualifiers
+ var ids = getAccessStack(ref);
+ for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
+ var id = ids_1[_i];
+ root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
+ }
+ return root;
}
- var rightPart = right;
- while (rightPart.left.kind !== 71 /* Identifier */) {
- rightPart = rightPart.left;
+ else {
+ // first shift type arguments
+ var innerParams = root.typeArguments;
+ (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
+ root.typeArguments = ref.typeArguments;
+ // then move qualifiers
+ var ids = getAccessStack(ref);
+ for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
+ var id = ids_2[_a];
+ root.typeName = ts.createQualifiedName(root.typeName, id);
+ }
+ return root;
}
- left.right = rightPart.left;
- rightPart.left = left;
- return right;
+ }
+ function getAccessStack(ref) {
+ var state = ref.typeName;
+ var ids = [];
+ while (!ts.isIdentifier(state)) {
+ ids.unshift(state.right);
+ state = state.left;
+ }
+ ids.unshift(state);
+ return ids;
}
function createTypeNodesFromResolvedType(resolvedType) {
var typeElements = [];
@@ -29168,32 +29762,47 @@ var ts;
}
return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
}
- function typeParameterToDeclaration(type, context, constraint) {
- if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ function typeParameterShadowsNameInScope(type, context) {
+ return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
+ }
+ function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
- var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
- var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.symbol.declarations[0] &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context);
+ var name = shouldUseGeneratedName
+ ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */)
+ : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
var defaultParameter = getDefaultFromTypeParameter(type);
var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
context.flags = savedContextFlags;
return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
}
+ function typeParameterToDeclaration(type, context, constraint) {
+ if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
+ }
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */);
- ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter);
+ if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 292 /* JSDocParameterTag */);
+ }
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
parameterType = getOptionalType(parameterType);
}
var parameterTypeNode = typeToTypeNodeHelper(parameterType, context);
var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone);
- var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined;
+ var isRest = parameterDeclaration ? ts.isRestParameter(parameterDeclaration) : parameterSymbol.isRestParameter;
+ var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined;
var name = parameterDeclaration
? parameterDeclaration.name ?
- parameterDeclaration.name.kind === 71 /* Identifier */ ?
- ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
- cloneBindingName(parameterDeclaration.name) :
+ parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
+ parameterDeclaration.name.kind === 145 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
+ cloneBindingName(parameterDeclaration.name) :
ts.symbolName(parameterSymbol)
: ts.symbolName(parameterSymbol);
var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined;
@@ -29213,7 +29822,7 @@ var ts;
}
}
}
- function lookupSymbolChain(symbol, context, meaning) {
+ function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning);
// Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
var chain;
@@ -29249,7 +29858,7 @@ var ts;
// If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
endOfChain ||
// If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
- !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) &&
+ (yieldModuleSymbol || !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol))) &&
// If a parent symbol is an anonymous type, don't write it.
!(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
return [symbol];
@@ -29281,22 +29890,54 @@ var ts;
}
return typeParameterNodes;
}
- function symbolToTypeNode(symbol, context, meaning) {
- var chain = lookupSymbolChain(symbol, context, meaning);
+ /**
+ * Given A[B][C][D], finds A[B]
+ */
+ function getTopmostIndexedAccessType(top) {
+ if (ts.isIndexedAccessTypeNode(top.objectType)) {
+ return getTopmostIndexedAccessType(top.objectType);
+ }
+ return top;
+ }
+ function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
+ var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
context.flags |= 16777216 /* InInitialEntityName */;
var rootName = getNameOfSymbolAsWritten(chain[0], context);
context.flags ^= 16777216 /* InInitialEntityName */;
var isTypeOf = meaning === 67216319 /* Value */;
if (ambientModuleSymbolRegex.test(rootName)) {
// module is root, must use `ImportTypeNode`
- var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined;
- var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context);
- return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf);
+ var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
+ var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
+ var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1)));
+ if (!nonRootParts || ts.isEntityName(nonRootParts)) {
+ if (nonRootParts) {
+ var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
+ lastId.typeArguments = undefined;
+ }
+ return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
+ }
+ else {
+ var splitNode = getTopmostIndexedAccessType(nonRootParts);
+ var qualifier = splitNode.objectType.typeName;
+ return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
+ }
}
- var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0);
- return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined);
- function createEntityNameFromSymbolChain(chain, index, stopper) {
- var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
+ var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
+ if (ts.isIndexedAccessTypeNode(entityName)) {
+ return entityName; // Indexed accesses can never be `typeof`
+ }
+ if (isTypeOf) {
+ return ts.createTypeQueryNode(entityName);
+ }
+ else {
+ var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
+ var lastTypeArgs = lastId.typeArguments;
+ lastId.typeArguments = undefined;
+ return ts.createTypeReferenceNode(entityName, lastTypeArgs);
+ }
+ function createAccessFromSymbolChain(chain, index, stopper) {
+ var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
var symbol = chain[index];
if (index === 0) {
context.flags |= 16777216 /* InInitialEntityName */;
@@ -29305,9 +29946,27 @@ var ts;
if (index === 0) {
context.flags ^= 16777216 /* InInitialEntityName */;
}
+ var parent = chain[index - 1];
+ if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) {
+ // Should use an indexed access
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (ts.isIndexedAccessTypeNode(LHS)) {
+ return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ else {
+ return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ }
var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
identifier.symbol = symbol;
- return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier;
+ if (index > stopper) {
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (!ts.isEntityName(LHS)) {
+ return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
+ }
+ return ts.createQualifiedName(LHS, identifier);
+ }
+ return identifier;
}
}
function symbolToName(symbol, context, meaning, expectsIdentifier) {
@@ -29456,6 +30115,24 @@ var ts;
return "default";
}
if (symbol.declarations && symbol.declarations.length) {
+ if (ts.some(symbol.declarations, hasExternalModuleSymbol) && context.enclosingDeclaration) {
+ var file_3 = ts.getDeclarationOfKind(symbol, 273 /* SourceFile */);
+ if (!file_3 || !context.tracker.moduleResolverHost) {
+ if (context.tracker.trackReferencedAmbientModule) {
+ var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
+ if (ts.length(ambientDecls)) {
+ for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
+ var decl = ambientDecls_1[_i];
+ context.tracker.trackReferencedAmbientModule(decl);
+ }
+ }
+ }
+ // ambient module, just use declaration/symbol name (fallthrough)
+ }
+ else {
+ return "\"" + ts.getResolvedExternalModuleName(context.tracker.moduleResolverHost, file_3, ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration))) + "\"";
+ }
+ }
var declaration = symbol.declarations[0];
var name = ts.getNameOfDeclaration(declaration);
if (name) {
@@ -29497,6 +30174,11 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ // Top-level jsdoc type aliases are considered exported
+ // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
+ return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
case 181 /* BindingElement */:
return isDeclarationVisible(node.parent.parent);
case 231 /* VariableDeclaration */:
@@ -30209,7 +30891,7 @@ var ts;
if (symbol.flags & 4194304 /* Prototype */) {
return links.type = getTypeOfPrototypeProperty(symbol);
}
- // CommonsJS require/module/exports all have type any.
+ // CommonsJS require and module both have type any.
if (symbol === requireSymbol || symbol === moduleSymbol) {
return links.type = anyType;
}
@@ -30219,6 +30901,10 @@ var ts;
return links.type = anyType;
}
// Handle export default expressions
+ if (ts.isSourceFile(declaration)) {
+ var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile);
+ return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType;
+ }
if (declaration.kind === 248 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
@@ -30239,7 +30925,7 @@ var ts;
declaration.kind === 184 /* PropertyAccessExpression */ && declaration.parent.kind === 199 /* BinaryExpression */) {
type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol);
}
- else if (ts.isJSDocPropertyTag(declaration)
+ else if (ts.isJSDocPropertyLikeTag(declaration)
|| ts.isPropertyAccessExpression(declaration)
|| ts.isIdentifier(declaration)
|| (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
@@ -30510,13 +31196,15 @@ var ts;
case 152 /* MethodSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
case 176 /* MappedType */:
case 170 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -30526,7 +31214,7 @@ var ts;
else if (node.kind === 170 /* ConditionalType */) {
return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
}
- var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray);
+ var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
var thisType = includeThisTypes &&
(node.kind === 234 /* ClassDeclaration */ || node.kind === 204 /* ClassExpression */ || node.kind === 235 /* InterfaceDeclaration */) &&
getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
@@ -30545,13 +31233,12 @@ var ts;
var result;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var node = _a[_i];
- if (node.kind === 235 /* InterfaceDeclaration */ || node.kind === 234 /* ClassDeclaration */ ||
- node.kind === 204 /* ClassExpression */ || node.kind === 236 /* TypeAliasDeclaration */) {
+ if (node.kind === 235 /* InterfaceDeclaration */ ||
+ node.kind === 234 /* ClassDeclaration */ ||
+ node.kind === 204 /* ClassExpression */ ||
+ ts.isTypeAlias(node)) {
var declaration = node;
- var typeParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
- if (typeParameters) {
- result = appendTypeParameters(result, typeParameters);
- }
+ result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
}
}
return result;
@@ -30828,9 +31515,9 @@ var ts;
return unknownType;
}
var declaration = ts.find(symbol.declarations, function (d) {
- return d.kind === 292 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */;
+ return ts.isJSDocTypeAlias(d) || d.kind === 236 /* TypeAliasDeclaration */;
});
- var typeNode = declaration.kind === 292 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type;
+ var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
// If typeNode is missing, we will error in checkJSDocTypedefTag.
var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType;
if (popTypeResolution()) {
@@ -31035,7 +31722,7 @@ var ts;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) &&
node.parameters.every(isThislessVariableLikeDeclaration) &&
- (!typeParameters || typeParameters.every(isThislessTypeParameter));
+ typeParameters.every(isThislessTypeParameter);
}
/**
* Returns true if the class or interface member given by the symbol is free of "this" references. The
@@ -31084,6 +31771,9 @@ var ts;
var symbol = type.symbol;
var members = getMembersOfSymbol(symbol);
type.declaredProperties = getNamedMembers(members);
+ // Start with signatures at empty array in case of recursive types
+ type.declaredCallSignatures = ts.emptyArray;
+ type.declaredConstructSignatures = ts.emptyArray;
type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
@@ -31213,9 +31903,9 @@ var ts;
// If we have an existing early-bound member, combine its declarations so that we can
// report an error at each declaration.
var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
- var name_3 = ts.declarationNameToString(decl.name);
- ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); });
- error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3);
+ var name_2 = ts.declarationNameToString(decl.name);
+ ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); });
+ error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2);
lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */);
}
lateSymbol.nameType = type;
@@ -31644,10 +32334,8 @@ var ts;
var templateType = getTemplateTypeFromMappedType(type.target || type);
var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
var templateModifiers = getMappedTypeModifiers(type);
- var constraintDeclaration = type.declaration.typeParameter.constraint;
var include = keyofStringsOnly ? 32 /* StringLiteral */ : 1120 /* StringOrNumberLiteralOrUnique */;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// We have a { [P in keyof T]: X }
for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
var prop = _a[_i];
@@ -31720,15 +32408,21 @@ var ts;
instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) :
unknownType);
}
+ function getConstraintDeclarationForMappedType(type) {
+ return type.declaration.typeParameter.constraint;
+ }
+ function isMappedTypeWithKeyofConstraintDeclaration(type) {
+ var constraintDeclaration = getConstraintDeclarationForMappedType(type);
+ return constraintDeclaration.kind === 174 /* TypeOperator */ &&
+ constraintDeclaration.operator === 128 /* KeyOfKeyword */;
+ }
function getModifiersTypeFromMappedType(type) {
if (!type.modifiersType) {
- var constraintDeclaration = type.declaration.typeParameter.constraint;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
// AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
// 'keyof T' to a literal union type and we can't recover T from that type.
- type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper);
+ type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper);
}
else {
// Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
@@ -31889,9 +32583,9 @@ var ts;
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
if (type.root.isDistributive) {
- var constraint = getConstraintOfType(type.checkType);
+ var constraint = getConstraintOfType(getSimplifiedType(type.checkType));
if (constraint) {
- var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
if (!(instantiated.flags & 16384 /* Never */)) {
return instantiated;
@@ -32278,9 +32972,10 @@ var ts;
// type checking functions).
function getTypeParametersFromDeclaration(declaration) {
var result;
- ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) {
+ for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
+ var node = _a[_i];
result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
- });
+ }
return result;
}
function symbolsToArray(symbols) {
@@ -32295,10 +32990,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJavaScriptFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 280 /* JSDocOptionalType */
+ node.type && node.type.kind === 282 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 280 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -32310,7 +33005,7 @@ var ts;
return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
}
function isOptionalParameter(node) {
- if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) {
+ if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
return true;
}
if (node.initializer) {
@@ -32327,6 +33022,13 @@ var ts;
}
return false;
}
+ function isOptionalJSDocParameterTag(node) {
+ if (!ts.isJSDocParameterTag(node)) {
+ return false;
+ }
+ var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */;
+ }
function createTypePredicateFromTypePredicateNode(node) {
var parameterName = node.parameterName;
var type = getTypeFromTypeNode(node.type);
@@ -32384,7 +33086,7 @@ var ts;
for (var i = numTypeArguments; i < numTypeParameters; i++) {
var mapper = createTypeMapper(typeParameters, typeArguments);
var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
- if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) {
+ if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) {
defaultType = anyType;
}
typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny);
@@ -32415,6 +33117,7 @@ var ts;
for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
var param = declaration.parameters[i];
var paramSymbol = param.symbol;
+ var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
// Include parameter symbol instead of property symbol in the signature
if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false);
@@ -32427,12 +33130,13 @@ var ts;
else {
parameters.push(paramSymbol);
}
- if (param.type && param.type.kind === 177 /* LiteralType */) {
+ if (type && type.kind === 177 /* LiteralType */) {
hasLiteralTypes = true;
}
// Record a new minimum argument count if this is not an optional parameter
- var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken ||
- iife && parameters.length > iife.arguments.length && !param.type ||
+ var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
+ param.initializer || param.questionToken || param.dotDotDotToken ||
+ iife && parameters.length > iife.arguments.length && !type ||
isUntypedSignatureInJSFile ||
isJSDocOptionalParameter(param);
if (!isOptionalParameter_1) {
@@ -32466,7 +33170,7 @@ var ts;
* 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
*/
function maybeAddJsSyntheticRestParameter(declaration, parameters) {
- if (!containsArgumentsReference(declaration)) {
+ if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
return false;
}
var lastParam = ts.lastOrUndefined(declaration.parameters);
@@ -32859,7 +33563,7 @@ var ts;
var isJs = ts.isInJavaScriptFile(node);
var isJsImplicitAny = !noImplicitAny && isJs;
if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
- var missingAugmentsTag = isJs && node.parent.kind !== 286 /* JSDocAugmentsTag */;
+ var missingAugmentsTag = isJs && node.parent.kind !== 289 /* JSDocAugmentsTag */;
var diag = minTypeArgumentCount === typeParameters.length
? missingAugmentsTag
? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag
@@ -33010,7 +33714,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node)) {
+ while (node && !ts.isStatement(node) && node.kind !== 285 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -33460,7 +34164,7 @@ var ts;
includes & 4096 /* Undefined */ ? includes & 16777216 /* NonWideningType */ ? undefinedType : undefinedWideningType :
neverType;
}
- return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments);
+ return getUnionTypeFromSortedList(typeSet, includes & 8374815 /* NotUnit */ ? 0 : 268435456 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments);
}
function getUnionTypePredicate(signatures) {
var first;
@@ -33497,7 +34201,7 @@ var ts;
: !ts.isIdentifierTypePredicate(b);
}
// This function assumes the constituent type list is sorted and deduplicated.
- function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) {
+ function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) {
if (types.length === 0) {
return neverType;
}
@@ -33508,7 +34212,7 @@ var ts;
var type = unionTypes.get(id);
if (!type) {
var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */);
- type = createType(131072 /* Union */ | propagatedFlags);
+ type = createType(131072 /* Union */ | propagatedFlags | unionOfUnitTypes);
unionTypes.set(id, type);
type.types = types;
/*
@@ -33525,7 +34229,8 @@ var ts;
function getTypeFromUnionTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var aliasSymbol = getAliasSymbolForTypeNode(node);
+ links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
}
return links.resolvedType;
}
@@ -33574,6 +34279,31 @@ var ts;
}
}
}
+ // When intersecting unions of unit types we can simply intersect based on type identity.
+ // Here we remove all unions of unit types from the given list and replace them with a
+ // a single union containing an intersection of the unit types.
+ function intersectUnionsOfUnitTypes(types) {
+ var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 268435456 /* UnionOfUnitTypes */) !== 0; });
+ var unionType = types[unionIndex];
+ var intersection = unionType.types;
+ var i = types.length - 1;
+ var _loop_5 = function () {
+ var t = types[i];
+ if (t.flags & 268435456 /* UnionOfUnitTypes */) {
+ intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); });
+ ts.orderedRemoveItemAt(types, i);
+ }
+ i--;
+ };
+ while (i > unionIndex) {
+ _loop_5();
+ }
+ if (intersection === unionType.types) {
+ return false;
+ }
+ types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 268435456 /* UnionOfUnitTypes */);
+ return true;
+ }
// We normalize combinations of intersection and union types based on the distributive property of the '&'
// operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
// types with union type constituents into equivalent union types with intersection type constituents and
@@ -33608,6 +34338,12 @@ var ts;
return typeSet[0];
}
if (includes & 131072 /* Union */) {
+ if (includes & 268435456 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) {
+ // When the intersection creates a reduced set (which might mean that *all* union types have
+ // disappeared), we restart the operation to get a new set of combined flags. Once we have
+ // reduced we'll never reduce again, so this occurs at most once.
+ return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
+ }
// We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
// the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072 /* Union */) !== 0; });
@@ -33629,7 +34365,8 @@ var ts;
function getTypeFromIntersectionTypeNode(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node));
+ var aliasSymbol = getAliasSymbolForTypeNode(node);
+ links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
}
return links.resolvedType;
}
@@ -33806,6 +34543,10 @@ var ts;
// Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
// the type itself if no transformation is possible.
function getSimplifiedIndexedAccessType(type) {
+ if (type.simplified) {
+ return type.simplified === circularConstraintType ? type : type.simplified;
+ }
+ type.simplified = circularConstraintType;
var objectType = type.objectType;
if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) {
// Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or
@@ -33824,7 +34565,7 @@ var ts;
regularTypes.push(t);
}
}
- return getUnionType([
+ return type.simplified = getUnionType([
getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)),
getIntersectionType(stringIndexTypes)
]);
@@ -33835,7 +34576,7 @@ var ts;
// eventually anyway, but it easier to reason about.
if (ts.some(objectType.types, isMappedTypeToNever)) {
var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); });
- return getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType));
+ return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType));
}
}
// If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
@@ -33843,15 +34584,15 @@ var ts;
// construct the type Box. We do not further simplify the result because mapped types can be recursive
// and we might never terminate.
if (isGenericMappedType(objectType)) {
- return substituteIndexedMappedType(objectType, type);
+ return type.simplified = substituteIndexedMappedType(objectType, type);
}
if (objectType.flags & 32768 /* TypeParameter */) {
var constraint = getConstraintFromTypeParameter(objectType);
if (constraint && isGenericMappedType(constraint)) {
- return substituteIndexedMappedType(constraint, type);
+ return type.simplified = substituteIndexedMappedType(constraint, type);
}
}
- return type;
+ return type.simplified = type;
}
function substituteIndexedMappedType(objectType, type) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]);
@@ -33916,7 +34657,7 @@ var ts;
var type = createObjectType(32 /* Mapped */, node.symbol);
type.declaration = node;
type.aliasSymbol = getAliasSymbolForTypeNode(node);
- type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
links.resolvedType = type;
// Eagerly resolve the constraint type which forces an error if the constraint type circularly
// references itself through one or more type aliases.
@@ -33939,14 +34680,14 @@ var ts;
var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */);
var combinedMapper;
if (root.inferTypeParameters) {
- var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
+ var context_1 = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
if (!isDeferred) {
// We don't want inferences from constraints as they may cause us to eagerly resolve the
// conditional type instead of deferring resolution. Also, we always want strict function
// types rules (i.e. proper contravariance) for inferences.
- inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
+ inferTypes(context_1.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context_1);
}
if (!isDeferred) {
// Return union of trueType and falseType for 'any' since it matches anything
@@ -34017,7 +34758,8 @@ var ts;
var links = getNodeLinks(node);
if (!links.resolvedType) {
var checkType = getTypeFromTypeNode(node.checkType);
- var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ var aliasSymbol = getAliasSymbolForTypeNode(node);
+ var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); });
var root = {
@@ -34030,7 +34772,7 @@ var ts;
inferTypeParameters: getInferTypeParameters(node),
outerTypeParameters: outerTypeParameters,
instantiations: undefined,
- aliasSymbol: getAliasSymbolForTypeNode(node),
+ aliasSymbol: aliasSymbol,
aliasTypeArguments: aliasTypeArguments
};
links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
@@ -34129,7 +34871,7 @@ var ts;
else {
var type = createObjectType(16 /* Anonymous */, node.symbol);
type.aliasSymbol = aliasSymbol;
- type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node);
+ type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
type = createArrayType(type);
}
@@ -34139,10 +34881,9 @@ var ts;
return links.resolvedType;
}
function getAliasSymbolForTypeNode(node) {
- return node.parent.kind === 236 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined;
+ return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined;
}
- function getAliasTypeArgumentsForTypeNode(node) {
- var symbol = getAliasSymbolForTypeNode(node);
+ function getTypeArgumentsForAliasSymbol(symbol) {
return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
}
/**
@@ -34321,8 +35062,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 119 /* AnyKeyword */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return anyType;
case 137 /* StringKeyword */:
return stringType;
@@ -34363,21 +35104,22 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 169 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 172 /* ParenthesizedType */:
- case 279 /* JSDocNonNullableType */:
- case 275 /* JSDocTypeExpression */:
+ case 281 /* JSDocNonNullableType */:
+ case 277 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
- case 281 /* JSDocFunctionType */:
+ case 286 /* JSDocTypeLiteral */:
+ case 283 /* JSDocFunctionType */:
+ case 287 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 174 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -34567,6 +35309,15 @@ var ts;
// aren't the right hand side of a generic type alias declaration we optimize by reducing the
// set of type parameters to those that are possibly referenced in the literal.
var declaration_1 = symbol.declarations[0];
+ if (ts.isInJavaScriptFile(declaration_1)) {
+ var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
+ if (paramTag) {
+ var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
+ if (paramSymbol) {
+ declaration_1 = paramSymbol.valueDeclaration;
+ }
+ }
+ }
var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
if (isJavaScriptConstructor(declaration_1)) {
var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
@@ -34608,8 +35359,8 @@ var ts;
// between the node and the type parameter declaration, if the node contains actual references to the
// type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
- var container_2 = tp.symbol.declarations[0].parent;
- if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_2; })) {
+ var container_3 = tp.symbol.declarations[0].parent;
+ if (ts.findAncestor(node, function (n) { return n.kind === 212 /* Block */ ? "quit" : n === container_3; })) {
return ts.forEachChild(node, containsReference);
}
}
@@ -35459,7 +36210,7 @@ var ts;
// check excess properties against discriminant type only, not the entire union
return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors);
}
- var _loop_5 = function (prop) {
+ var _loop_6 = function (prop) {
if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
if (reportErrors) {
// We know *exactly* where things went wrong when comparing the types.
@@ -35496,7 +36247,7 @@ var ts;
};
for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
var prop = _a[_i];
- var state_3 = _loop_5(prop);
+ var state_3 = _loop_6(prop);
if (typeof state_3 === "object")
return state_3.value;
}
@@ -35802,16 +36553,19 @@ var ts;
}
}
var constraint = getConstraintForRelation(source);
- if (!constraint || constraint.flags & 1 /* Any */) {
+ if (!constraint || (source.flags & 32768 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
// A type variable with no constraint is not related to the non-primitive object type.
if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728 /* NonPrimitive */))) {
errorInfo = saveErrorInfo;
return result;
}
}
- else if (result = isRelatedTo(constraint, target, reportErrors)) {
- errorInfo = saveErrorInfo;
- return result;
+ else {
+ var instantiated = getTypeWithThisArgument(constraint, source);
+ if (result = isRelatedTo(instantiated, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
}
}
else if (source.flags & 524288 /* Index */) {
@@ -35939,10 +36693,10 @@ var ts;
var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
if (modifiersRelated) {
- var result_1;
- if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
+ var result_2;
+ if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
- return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
+ return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
}
}
return 0 /* False */;
@@ -38049,7 +38803,7 @@ var ts;
if (type.flags & 131072 /* Union */) {
var types = type.types;
var filtered = ts.filter(types, f);
- return filtered === types ? type : getUnionTypeFromSortedList(filtered);
+ return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 268435456 /* UnionOfUnitTypes */);
}
return f(type) ? type : neverType;
}
@@ -39285,7 +40039,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 281 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 283 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -39721,7 +40475,7 @@ var ts;
// except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}`
var type = getContextualType(binaryExpression);
return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ?
- getTypeOfExpression(left, /*cache*/ true) : type;
+ getTypeOfExpression(left) : type;
case 53 /* AmpersandAmpersandToken */:
case 26 /* CommaToken */:
return node === right ? getContextualType(binaryExpression) : undefined;
@@ -40000,8 +40754,18 @@ var ts;
return unknownType;
}
}
- if (context.typeArguments) {
- signatures = ts.mapDefined(signatures, function (s) { return getJsxSignatureTypeArgumentInstantiation(s, context, isJs); });
+ var links = getNodeLinks(context);
+ if (!links.resolvedSignatures) {
+ links.resolvedSignatures = ts.createMap();
+ }
+ var cacheKey = "" + getTypeId(valueType);
+ var cachedResolved = links.resolvedSignatures.get(cacheKey);
+ if (cachedResolved && cachedResolved !== resolvingSignaturesArray) {
+ signatures = cachedResolved;
+ }
+ else if (!cachedResolved) {
+ links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray);
+ links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures));
}
return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */);
}
@@ -40312,7 +41076,7 @@ var ts;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 179 /* ObjectBindingPattern */ || contextualType.pattern.kind === 183 /* ObjectLiteralExpression */);
- var isInJSFile = ts.isInJavaScriptFile(node);
+ var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node);
var isJSObjectLiteral = !contextualType && isInJSFile;
var typeFlags = 0;
var patternWithComputedProperties = false;
@@ -40908,6 +41672,37 @@ var ts;
}
return undefined;
}
+ function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) {
+ var links = getNodeLinks(openingLikeElement);
+ if (!links.resolvedSignatures) {
+ links.resolvedSignatures = ts.createMap();
+ }
+ var cacheKey = "" + getTypeId(elementType);
+ if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) {
+ return;
+ }
+ else if (links.resolvedSignatures.get(cacheKey)) {
+ return links.resolvedSignatures.get(cacheKey);
+ }
+ links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray);
+ // Resolve the signatures, preferring constructor
+ var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
+ if (signatures.length === 0) {
+ // No construct signatures, try call signatures
+ signatures = getSignaturesOfType(elementType, 0 /* Call */);
+ if (signatures.length === 0) {
+ // We found no signatures at all, which is an error
+ if (reportErrors) {
+ error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName));
+ }
+ return;
+ }
+ }
+ // Instantiate in context of source type
+ var results = instantiateJsxSignatures(openingLikeElement, signatures);
+ links.resolvedSignatures.set(cacheKey, results);
+ return results;
+ }
/**
* Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType.
* For instance:
@@ -40963,19 +41758,10 @@ var ts;
return anyType;
}
// Get the element instance type (the result of newing or invoking this tag)
- // Resolve the signatures, preferring constructor
- var signatures = getSignaturesOfType(elementType, 1 /* Construct */);
- if (signatures.length === 0) {
- // No construct signatures, try call signatures
- signatures = getSignaturesOfType(elementType, 0 /* Call */);
- if (signatures.length === 0) {
- // We found no signatures at all, which is an error
- error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName));
- return unknownType;
- }
+ var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true);
+ if (!ts.length(instantiatedSignatures)) {
+ return unknownType;
}
- // Instantiate in context of source type
- var instantiatedSignatures = instantiateJsxSignatures(openingLikeElement, signatures);
var elemInstanceType = getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */);
// If we should include all stateless attributes type, then get all attributes type from all stateless function signature.
// Otherwise get only attributes type from the signature picked by choose-overload logic.
@@ -41199,7 +41985,7 @@ var ts;
// Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
if (ts.length(openingLikeElement.attributes.properties)) {
var reportedError = false;
- var _loop_6 = function (prop) {
+ var _loop_7 = function (prop) {
if (ts.isJsxSpreadAttribute(prop))
return "continue";
var name = ts.idText(prop.name);
@@ -41213,7 +41999,7 @@ var ts;
};
for (var _b = 0, _c = openingLikeElement.attributes.properties; _b < _c.length; _b++) {
var prop = _c[_b];
- _loop_6(prop);
+ _loop_7(prop);
}
if (reportedError) {
return;
@@ -42484,10 +43270,10 @@ var ts;
var isDecorator = node.kind === 149 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
var typeArguments;
- if (!isDecorator && !isJsxOpeningOrSelfClosingElement) {
+ if (!isDecorator) {
typeArguments = node.typeArguments;
// We already perform checking on the type arguments on the class declaration itself.
- if (isTaggedTemplate || node.expression.kind !== 97 /* SuperKeyword */) {
+ if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) {
ts.forEach(typeArguments, checkSourceElement);
}
}
@@ -43012,28 +43798,6 @@ var ts;
*/
function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) {
ts.Debug.assert(!(elementType.flags & 131072 /* Union */));
- return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray);
- }
- /**
- * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature.
- * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible
- * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element.
- * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
- * the function will fill it up with appropriate candidate signatures
- * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions.
- * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures
- */
- function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) {
- // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType)
- if (elementType.flags & 131072 /* Union */) {
- var types = elementType.types;
- var result = void 0;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var type = types_16[_i];
- result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray);
- }
- return result;
- }
var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */);
if (callSignatures && callSignatures.length > 0) {
return resolveCall(openingLikeElement, callSignatures, candidatesOutArray);
@@ -43053,7 +43817,18 @@ var ts;
case 256 /* JsxOpeningElement */:
case 255 /* JsxSelfClosingElement */:
// This code-path is called by language service
- return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature;
+ var exprTypes = checkExpression(node.tagName);
+ return forEachType(exprTypes, function (exprType) {
+ var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray);
+ if (sfcResult && sfcResult !== unknownSignature) {
+ return sfcResult;
+ }
+ var sigs = getInstantiatedJsxSignatures(node, exprType);
+ if (candidatesOutArray && ts.length(sigs)) {
+ candidatesOutArray.push.apply(candidatesOutArray, sigs);
+ }
+ return ts.length(sigs) ? sigs[0] : unknownSignature;
+ }) || unknownSignature;
}
ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -43251,8 +44026,8 @@ var ts;
if (allowSyntheticDefaultImports && type && type !== unknownType) {
var synthType = type;
if (!synthType.syntheticType) {
- var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
+ var file_4 = ts.find(originalSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_4, originalSymbol, /*dontResolveAlias*/ false);
if (hasSyntheticDefault) {
var memberTable = ts.createSymbolTable();
var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
@@ -43706,7 +44481,7 @@ var ts;
checkGrammarForGenerator(node);
}
var links = getNodeLinks(node);
- var type = getTypeOfSymbol(node.symbol);
+ var type = getTypeOfSymbol(getMergedSymbol(node.symbol));
if (isTypeAny(type)) {
return type;
}
@@ -43940,8 +44715,8 @@ var ts;
}
if (type.flags & 393216 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
- var t = types_17[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -45036,7 +45811,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
- if (node.kind !== 159 /* IndexSignature */ && node.kind !== 281 /* JSDocFunctionType */) {
+ if (node.kind !== 159 /* IndexSignature */ && node.kind !== 283 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -45499,7 +46274,7 @@ var ts;
n.parent.kind !== 234 /* ClassDeclaration */ &&
n.parent.kind !== 204 /* ClassExpression */ &&
n.flags & 4194304 /* Ambient */) {
- if (!(flags & 2 /* Ambient */)) {
+ if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
// It is nested in an ambient context, which means it is automatically exported
flags |= 1 /* Export */;
}
@@ -45769,8 +46544,9 @@ var ts;
switch (d.kind) {
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
- // A jsdoc typedef is, by definition, a type alias
- case 292 /* JSDocTypedefTag */:
+ // A jsdoc typedef and callback are, by definition, type aliases
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 238 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -45792,10 +46568,10 @@ var ts;
case 242 /* ImportEqualsDeclaration */:
case 245 /* NamespaceImport */:
case 244 /* ImportClause */:
- var result_2 = 0 /* None */;
+ var result_3 = 0 /* None */;
var target = resolveAlias(getSymbolOfNode(d));
- ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); });
- return result_2;
+ ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); });
+ return result_3;
case 231 /* VariableDeclaration */:
case 181 /* BindingElement */:
case 233 /* FunctionDeclaration */:
@@ -46239,7 +47015,7 @@ var ts;
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
}
}
- function checkJSDocTypedefTag(node) {
+ function checkJSDocTypeAliasTag(node) {
if (!node.typeExpression) {
// If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
@@ -46363,7 +47139,13 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
- if (potentiallyUnusedIdentifiers) {
+ if (produceDiagnostics) {
+ var sourceFile = ts.getSourceFileOfNode(node);
+ var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
+ if (!potentiallyUnusedIdentifiers) {
+ potentiallyUnusedIdentifiers = [];
+ allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
+ }
// TODO: GH#22580
// Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
potentiallyUnusedIdentifiers.push(node);
@@ -46373,10 +47155,6 @@ var ts;
for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
var node = potentiallyUnusedIdentifiers_1[_i];
switch (node.kind) {
- case 273 /* SourceFile */:
- case 238 /* ModuleDeclaration */:
- checkUnusedModuleMembers(node, addDiagnostic);
- break;
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
checkUnusedClassMembers(node, addDiagnostic);
@@ -46385,6 +47163,8 @@ var ts;
case 235 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 273 /* SourceFile */:
+ case 238 /* ModuleDeclaration */:
case 212 /* Block */:
case 240 /* CaseBlock */:
case 219 /* ForStatement */:
@@ -46417,33 +47197,6 @@ var ts;
}
}
}
- function checkUnusedLocalsAndParameters(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- node.locals.forEach(function (local) {
- // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
- // If it's a type parameter merged with a parameter, check if the parameter-side is used.
- if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) {
- if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) {
- var parameter = ts.getRootDeclaration(local.valueDeclaration);
- var name = ts.getNameOfDeclaration(local.valueDeclaration);
- if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
- addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
- }
- }
- else {
- ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); });
- }
- }
- });
- }
- }
- function isRemovedPropertyFromObjectSpread(node) {
- if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) {
- var lastElement = ts.lastOrUndefined(node.parent.elements);
- return lastElement !== node && !!lastElement.dotDotDotToken;
- }
- return false;
- }
function errorUnusedLocal(declaration, name, addDiagnostic) {
var node = ts.getNameOfDeclaration(declaration) || declaration;
if (isIdentifierThatStartsWithUnderScore(node)) {
@@ -46453,10 +47206,8 @@ var ts;
return;
}
}
- if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) {
- var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
- }
+ var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
}
function parameterNameStartsWithUnderscore(parameterName) {
return parameterName && isIdentifierThatStartsWithUnderScore(parameterName);
@@ -46504,7 +47255,7 @@ var ts;
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- if (!(node.flags & 4194304 /* Ambient */) && typeParameters && ts.last(getSymbolOfNode(node).declarations) === node) {
+ if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) {
for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
var typeParameter = typeParameters_2[_i];
if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) {
@@ -46513,50 +47264,91 @@ var ts;
}
}
}
- function checkUnusedModuleMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
- var unusedImports_1 = ts.createMap();
- node.locals.forEach(function (local) {
- if (local.isReferenced || local.exportSymbol)
- return;
- for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
- var declaration = _a[_i];
- if (ts.isAmbientModule(declaration))
- continue;
- if (isImportedDeclaration(declaration)) {
- var importClause = importClauseFromImported(declaration);
- var key = String(getNodeId(importClause));
- var group_1 = unusedImports_1.get(key);
- if (group_1) {
- group_1[1].push(declaration);
- }
- else {
- unusedImports_1.set(key, [importClause, [declaration]]);
+ function addToGroup(map, key, value, getKey) {
+ var keyString = String(getKey(key));
+ var group = map.get(keyString);
+ if (group) {
+ group[1].push(value);
+ }
+ else {
+ map.set(keyString, [key, [value]]);
+ }
+ }
+ function tryGetRootParameterDeclaration(node) {
+ return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
+ }
+ function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
+ if (nodeWithLocals.flags & 4194304 /* Ambient */)
+ return;
+ // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
+ var unusedImports = ts.createMap();
+ var unusedDestructures = ts.createMap();
+ nodeWithLocals.locals.forEach(function (local) {
+ // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
+ // If it's a type parameter merged with a parameter, check if the parameter-side is used.
+ if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
+ return;
+ }
+ for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ if (ts.isAmbientModule(declaration))
+ continue;
+ if (isImportedDeclaration(declaration)) {
+ addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
+ }
+ else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
+ // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
+ var lastElement = ts.last(declaration.parent.elements);
+ if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
+ addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
+ }
+ }
+ else {
+ var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
+ if (parameter) {
+ var name = ts.getNameOfDeclaration(local.valueDeclaration);
+ if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
+ addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
}
}
else {
errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
}
}
- });
- unusedImports_1.forEach(function (_a) {
- var importClause = _a[0], unuseds = _a[1];
- var importDecl = importClause.parent;
- if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
- for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
- var unused = unuseds_1[_i];
- errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
- }
+ }
+ });
+ unusedImports.forEach(function (_a) {
+ var importClause = _a[0], unuseds = _a[1];
+ var importDecl = importClause.parent;
+ if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
+ for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
+ var unused = unuseds_1[_i];
+ errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
}
- else if (unuseds.length === 1) {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else if (unuseds.length === 1) {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
+ }
+ });
+ unusedDestructures.forEach(function (_a) {
+ var bindingPattern = _a[0], bindingElements = _a[1];
+ var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
+ if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) {
+ for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
+ var e = bindingElements_1[_i];
+ addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier))));
}
- else {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)));
- }
- });
- }
+ }
+ else if (bindingElements.length === 1) {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))));
+ }
+ else {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
+ }
+ });
}
function isImportedDeclaration(node) {
return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */;
@@ -47731,7 +48523,7 @@ var ts;
var declaration = declarations_6[_i];
// If this declaration has too few or too many type parameters, we report an error
var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
- var numTypeParameters = ts.length(sourceParameters);
+ var numTypeParameters = sourceParameters.length;
if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
return false;
}
@@ -47879,7 +48671,7 @@ var ts;
function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
// iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
var issuedMemberError = false;
- var _loop_7 = function (member) {
+ var _loop_8 = function (member) {
if (ts.hasStaticModifier(member)) {
return "continue";
}
@@ -47898,7 +48690,7 @@ var ts;
};
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- _loop_7(member);
+ _loop_8(member);
}
if (!issuedMemberError) {
// check again with diagnostics to generate a less-specific error
@@ -48747,9 +49539,9 @@ var ts;
}
}
// Checks for export * conflicts
- var exports = getExportsOfModule(moduleSymbol);
- if (exports) {
- exports.forEach(function (_a, id) {
+ var exports_1 = getExportsOfModule(moduleSymbol);
+ if (exports_1) {
+ exports_1.forEach(function (_a, id) {
var declarations = _a.declarations, flags = _a.flags;
if (id === "__export") {
return;
@@ -48855,27 +49647,28 @@ var ts;
return checkInferType(node);
case 178 /* ImportType */:
return checkImportType(node);
- case 286 /* JSDocAugmentsTag */:
+ case 289 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 292 /* JSDocTypedefTag */:
- return checkJSDocTypedefTag(node);
- case 288 /* JSDocParameterTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ return checkJSDocTypeAliasTag(node);
+ case 292 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
checkSignatureDeclaration(node);
// falls through
- case 279 /* JSDocNonNullableType */:
- case 278 /* JSDocNullableType */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
- case 284 /* JSDocTypeLiteral */:
+ case 281 /* JSDocNonNullableType */:
+ case 280 /* JSDocNullableType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
+ case 286 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 175 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -48987,8 +49780,8 @@ var ts;
var paramTag = parent.parent;
if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) {
// Else we will add a diagnostic, see `checkJSDocVariadicType`.
- var host_2 = ts.getHostSignatureFromJSDoc(paramTag);
- if (host_2) {
+ var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
+ if (host_1) {
/*
Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
So in the following situation we will not create an array type:
@@ -48996,7 +49789,7 @@ var ts;
function f(a) {}
Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
*/
- var lastParamDeclaration = ts.lastOrUndefined(host_2.parameters);
+ var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
if (!lastParamDeclaration ||
symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
@@ -49059,6 +49852,9 @@ var ts;
return ts.Debug.assertNever(kind);
}
}
+ function getPotentiallyUnusedIdentifiers(sourceFile) {
+ return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
+ }
// Fully type check a source file and collect the relevant diagnostics.
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
@@ -49074,25 +49870,19 @@ var ts;
ts.clear(potentialThisCollisions);
ts.clear(potentialNewTargetCollisions);
deferredNodes = [];
- if (produceDiagnostics) {
- ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
- allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
- }
ts.forEach(node.statements, checkSourceElement);
checkDeferredNodes();
if (ts.isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
- checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) {
+ checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
});
}
deferredNodes = undefined;
- seenPotentiallyUnusedIdentifiers.clear();
- potentiallyUnusedIdentifiers = undefined;
if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
@@ -49388,10 +50178,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 288 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 292 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 291 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 295 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -49931,6 +50721,7 @@ var ts;
function isRequiredInitializedParameter(parameter) {
return strictNullChecks &&
!isOptionalParameter(parameter) &&
+ !ts.isJSDocParameterTag(parameter) &&
parameter.initializer &&
!ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
}
@@ -50181,7 +50972,22 @@ var ts;
var symbol = node && getSymbolOfNode(node);
return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
},
- getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; },
+ getAllAccessorDeclarations: function (accessor) {
+ accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration);
+ var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */;
+ var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
+ var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
+ var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
+ var setAccessor = accessor.kind === 156 /* SetAccessor */ ? accessor : otherAccessor;
+ var getAccessor = accessor.kind === 155 /* GetAccessor */ ? accessor : otherAccessor;
+ return {
+ firstAccessor: firstAccessor,
+ secondAccessor: secondAccessor,
+ setAccessor: setAccessor,
+ getAccessor: getAccessor
+ };
+ }
};
function isInHeritageClause(node) {
return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 267 /* HeritageClause */;
@@ -50217,8 +51023,8 @@ var ts;
var decl = _a[_i];
// check meaning of the local symbol to see if declaration needs to be analyzed further
if (decl.symbol && decl.symbol.flags & meaning) {
- var file = ts.getSourceFileOfNode(decl);
- var typeReferenceDirective = fileToDirective.get(file.path);
+ var file_5 = ts.getSourceFileOfNode(decl);
+ var typeReferenceDirective = fileToDirective.get(file_5.path);
if (typeReferenceDirective) {
(typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
}
@@ -50253,8 +51059,8 @@ var ts;
// check that at least one declaration of top level symbol originates from type declaration file
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
- var file = ts.getSourceFileOfNode(decl);
- if (fileToDirective.has(file.path)) {
+ var file_6 = ts.getSourceFileOfNode(decl);
+ if (fileToDirective.has(file_6.path)) {
return true;
}
}
@@ -50272,25 +51078,25 @@ var ts;
function initializeTypeChecker() {
// Bind all source files and propagate errors
for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
- var file = _a[_i];
- ts.bindSourceFile(file, compilerOptions);
+ var file_7 = _a[_i];
+ ts.bindSourceFile(file_7, compilerOptions);
}
// Initialize global symbol table
var augmentations;
for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
- var file = _c[_b];
- if (!ts.isExternalOrCommonJsModule(file)) {
- mergeSymbolTable(globals, file.locals);
+ var file_8 = _c[_b];
+ if (!ts.isExternalOrCommonJsModule(file_8)) {
+ mergeSymbolTable(globals, file_8.locals);
}
- if (file.patternAmbientModules && file.patternAmbientModules.length) {
- patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
+ if (file_8.patternAmbientModules && file_8.patternAmbientModules.length) {
+ patternAmbientModules = ts.concatenate(patternAmbientModules, file_8.patternAmbientModules);
}
- if (file.moduleAugmentations.length) {
- (augmentations || (augmentations = [])).push(file.moduleAugmentations);
+ if (file_8.moduleAugmentations.length) {
+ (augmentations || (augmentations = [])).push(file_8.moduleAugmentations);
}
- if (file.symbol && file.symbol.globalExports) {
+ if (file_8.symbol && file_8.symbol.globalExports) {
// Merge in UMD exports with first-in-wins semantics (see #9771)
- var source = file.symbol.globalExports;
+ var source = file_8.symbol.globalExports;
source.forEach(function (sourceSymbol, id) {
if (!globals.has(id)) {
globals.set(id, sourceSymbol);
@@ -50742,7 +51548,7 @@ var ts;
}
function checkGrammarClassLikeDeclaration(node) {
var file = ts.getSourceFileOfNode(node);
- return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(ts.getEffectiveTypeParameterDeclarations(node), file);
+ return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
}
function checkGrammarArrowFunction(node, file) {
if (!ts.isArrowFunction(node)) {
@@ -51427,8 +52233,8 @@ var ts;
}
function checkGrammarConstructorTypeParameters(node) {
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
- if (typeParameters) {
- var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end;
+ if (ts.isNodeArray(typeParameters)) {
+ var pos = typeParameters.pos, end = typeParameters.end;
return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
}
}
@@ -51578,7 +52384,7 @@ var ts;
}
function checkGrammarImportCallExpression(node) {
if (moduleKind === ts.ModuleKind.ES2015) {
- return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules);
+ return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext);
}
if (node.typeArguments) {
return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
@@ -51657,10 +52463,8 @@ var ts;
if (!elements || elements === ts.emptyArray) {
elements = [];
}
- else {
- if (ts.isNodeArray(elements)) {
- return elements;
- }
+ else if (ts.isNodeArray(elements)) {
+ return elements;
}
var array = elements;
array.pos = -1;
@@ -51720,6 +52524,13 @@ var ts;
node.text = text;
return node;
}
+ ts.createStringLiteral = createStringLiteral;
+ function createRegularExpressionLiteral(text) {
+ var node = createSynthesizedNode(12 /* RegularExpressionLiteral */);
+ node.text = text;
+ return node;
+ }
+ ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
function createLiteralFromNode(sourceNode) {
var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
node.textSourceNode = sourceNode;
@@ -51753,7 +52564,7 @@ var ts;
recordTempVariable(name);
}
if (reservedInNestedScopes) {
- name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */;
+ name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
}
return name;
}
@@ -51779,7 +52590,7 @@ var ts;
/** Create a unique name based on the supplied text. */
function createOptimisticUniqueName(text) {
var name = createIdentifier(text);
- name.autoGenerateFlags = 3 /* Unique */ | 32 /* Optimistic */;
+ name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
@@ -51788,18 +52599,15 @@ var ts;
/** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
function createFileLevelUniqueName(text) {
var name = createOptimisticUniqueName(text);
- name.autoGenerateFlags |= 64 /* FileLevel */;
+ name.autoGenerateFlags |= 32 /* FileLevel */;
return name;
}
ts.createFileLevelUniqueName = createFileLevelUniqueName;
- function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) {
- var name = createIdentifier("");
- name.autoGenerateFlags = 4 /* Node */;
+ function getGeneratedNameForNode(node, flags) {
+ var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : "");
+ name.autoGenerateFlags = 4 /* Node */ | flags;
name.autoGenerateId = nextAutoGenerateId;
name.original = node;
- if (shouldSkipNameGenerationScope) {
- name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */;
- }
nextAutoGenerateId++;
return name;
}
@@ -51890,7 +52698,7 @@ var ts;
ts.updateQualifiedName = updateQualifiedName;
function parenthesizeForComputedName(expression) {
return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) ||
- expression.kind === 297 /* CommaListExpression */ ?
+ expression.kind === 301 /* CommaListExpression */ ?
createParen(expression) :
expression;
}
@@ -52940,6 +53748,13 @@ var ts;
return block;
}
ts.createBlock = createBlock;
+ /* @internal */
+ function createExpressionStatement(expression) {
+ var node = createSynthesizedNode(215 /* ExpressionStatement */);
+ node.expression = expression;
+ return node;
+ }
+ ts.createExpressionStatement = createExpressionStatement;
function updateBlock(node, statements) {
return node.statements !== statements
? updateNode(createBlock(statements, node.multiLine), node)
@@ -52966,9 +53781,7 @@ var ts;
}
ts.createEmptyStatement = createEmptyStatement;
function createStatement(expression) {
- var node = createSynthesizedNode(215 /* ExpressionStatement */);
- node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
- return node;
+ return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression));
}
ts.createStatement = createStatement;
function updateStatement(node, expression) {
@@ -53864,7 +54677,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(295 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(299 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -53876,7 +54689,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(303 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53888,7 +54701,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(298 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(302 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53903,7 +54716,7 @@ var ts;
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(296 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(300 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -53919,7 +54732,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 297 /* CommaListExpression */) {
+ if (node.kind === 301 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) {
@@ -53929,7 +54742,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(297 /* CommaListExpression */);
+ var node = createSynthesizedNode(301 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -53940,15 +54753,31 @@ var ts;
: node;
}
ts.updateCommaList = updateCommaList;
- function createBundle(sourceFiles) {
+ function createBundle(sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
var node = ts.createNode(274 /* Bundle */);
+ node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function updateBundle(node, sourceFiles) {
- if (node.sourceFiles !== sourceFiles) {
- return createBundle(sourceFiles);
+ function createUnparsedSourceFile(text) {
+ var node = ts.createNode(275 /* UnparsedSource */);
+ node.text = text;
+ return node;
+ }
+ ts.createUnparsedSourceFile = createUnparsedSourceFile;
+ function createInputFiles(javascript, declaration) {
+ var node = ts.createNode(276 /* InputFiles */);
+ node.javascriptText = javascript;
+ node.declarationText = declaration;
+ return node;
+ }
+ ts.createInputFiles = createInputFiles;
+ function updateBundle(node, sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
+ if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
+ return createBundle(sourceFiles, prepends);
}
return node;
}
@@ -54220,6 +55049,15 @@ var ts;
return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
}
ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
+ function moveSyntheticComments(node, original) {
+ setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
+ setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
+ var emit = getOrCreateEmitNode(original);
+ emit.leadingComments = undefined;
+ emit.trailingComments = undefined;
+ return node;
+ }
+ ts.moveSyntheticComments = moveSyntheticComments;
/**
* Gets the constant value to emit for an expression.
*/
@@ -55192,7 +56030,7 @@ var ts;
// if should be wrapped in parens since comma operator has the lowest precedence
var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
return emittedExpression.kind === 199 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ ||
- emittedExpression.kind === 297 /* CommaListExpression */
+ emittedExpression.kind === 301 /* CommaListExpression */
? ts.createParen(e)
: e;
}
@@ -55212,7 +56050,7 @@ var ts;
var check = ts.skipPartiallyEmittedExpressions(e);
return (check.kind === 204 /* ClassExpression */ ||
check.kind === 191 /* FunctionExpression */ ||
- check.kind === 297 /* CommaListExpression */ ||
+ check.kind === 301 /* CommaListExpression */ ||
ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */)
? ts.createParen(e)
: e;
@@ -55333,6 +56171,7 @@ var ts;
switch (member.kind) {
case 164 /* TypeQuery */:
case 174 /* TypeOperator */:
+ case 171 /* InferType */:
return ts.createParenthesizedType(member);
}
return parenthesizeElementTypeMember(member);
@@ -55376,7 +56215,7 @@ var ts;
case 184 /* PropertyAccessExpression */:
node = node.expression;
continue;
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -55406,7 +56245,7 @@ var ts;
case 207 /* AsExpression */:
case 208 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -55443,7 +56282,7 @@ var ts;
case 189 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 207 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 208 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 300 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -55931,7 +56770,7 @@ var ts;
statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements);
}
var declarations = context.endLexicalEnvironment();
- return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements);
+ return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements);
}
ts.visitLexicalEnvironment = visitLexicalEnvironment;
/**
@@ -56228,9 +57067,9 @@ var ts;
case 273 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -56286,7 +57125,7 @@ var ts;
case 214 /* EmptyStatement */:
case 205 /* OmittedExpression */:
case 230 /* DebuggerStatement */:
- case 295 /* NotEmittedStatement */:
+ case 299 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -56665,10 +57504,10 @@ var ts;
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 300 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 297 /* CommaListExpression */:
+ case 301 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -56682,8 +57521,8 @@ var ts;
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements)
- : ts.addRange(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements)
+ : ts.prependRange(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -56833,16 +57672,6 @@ var ts;
return node ? ts.getNodeId(node) : 0;
}
ts.getOriginalNodeId = getOriginalNodeId;
- function getNamedImportCount(node) {
- if (!(node.importClause && node.importClause.namedBindings))
- return 0;
- var names = node.importClause.namedBindings;
- if (!names)
- return 0;
- if (!ts.isNamedImports(names))
- return 0;
- return names.elements.length;
- }
function containsDefaultReference(node) {
if (!node)
return false;
@@ -56853,12 +57682,40 @@ var ts;
function isNamedDefaultReference(e) {
return e.propertyName && e.propertyName.escapedText === "default" /* Default */;
}
+ function chainBundle(transformSourceFile) {
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ return node.kind === 273 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ }
+ function transformBundle(node) {
+ return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
+ }
+ }
+ ts.chainBundle = chainBundle;
function getImportNeedsImportStarHelper(node) {
- return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings));
+ if (!!ts.getNamespaceDeclarationNode(node)) {
+ return true;
+ }
+ var bindings = node.importClause && node.importClause.namedBindings;
+ if (!bindings) {
+ return false;
+ }
+ if (!ts.isNamedImports(bindings))
+ return false;
+ var defaultRefCount = 0;
+ for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
+ var binding = _a[_i];
+ if (isNamedDefaultReference(binding)) {
+ defaultRefCount++;
+ }
+ }
+ // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
+ return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
}
ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
function getImportNeedsImportDefaultHelper(node) {
- return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings));
+ // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
+ return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings)));
}
ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
@@ -57595,7 +58452,21 @@ var ts;
* at the next execution site, in document order
*/
var pendingExpressions;
- return transformSourceFile;
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ if (node.kind === 274 /* Bundle */) {
+ return transformBundle(node);
+ }
+ return transformSourceFile(node);
+ }
+ function transformBundle(node) {
+ return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
+ if (prepend.kind === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.javascriptText);
+ }
+ return prepend;
+ }));
+ }
/**
* Transform TypeScript-specific syntax in a SourceFile.
*
@@ -58085,7 +58956,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, context.endLexicalEnvironment());
+ ts.prependRange(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -58290,7 +59161,7 @@ var ts;
// record an alias as the class name is not in scope for statics.
enableSubstitutionForClassAliases();
var alias = ts.getSynthesizedClone(temp);
- alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */;
+ alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
classAliases[ts.getOriginalNodeId(node)] = alias;
}
// To preserve the behavior of the old emitter, we explicitly indent
@@ -58567,7 +59438,7 @@ var ts;
function transformInitializedProperty(property, receiver) {
// We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
- ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */)))
+ ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
: property.name;
var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression);
var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
@@ -59597,6 +60468,11 @@ var ts;
// we can safely elide the parentheses here, as a new synthetic
// ParenthesizedExpression will be inserted if we remove parentheses too
// aggressively.
+ // HOWEVER - if there are leading comments on the expression itself, to handle ASI
+ // correctly for return and throw, we must keep the parenthesis
+ if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
+ return ts.updateParen(node, expression);
+ }
return ts.createPartiallyEmittedExpression(expression, node);
}
return ts.visitEachChild(node, visitor, context);
@@ -59702,8 +60578,9 @@ var ts;
currentNamespaceContainerName = localName;
var statements = [];
startLexicalEnvironment();
- ts.addRange(statements, ts.map(node.members, transformEnumMember));
- ts.addRange(statements, endLexicalEnvironment());
+ var members = ts.map(node.members, transformEnumMember);
+ ts.prependRange(statements, endLexicalEnvironment());
+ ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
/*multiLine*/ true);
@@ -59943,7 +60820,7 @@ var ts;
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -60480,7 +61357,7 @@ var ts;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -60752,7 +61629,7 @@ var ts;
var statements = [];
var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
@@ -60774,7 +61651,7 @@ var ts;
var declarations = endLexicalEnvironment();
if (ts.some(declarations)) {
var block = ts.convertToFunctionBody(expression);
- result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements));
+ result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
}
else {
result = expression;
@@ -60964,7 +61841,7 @@ var ts;
var enabledSubstitutions;
var enclosingFunctionFlags;
var enclosingSuperContainerFlags = 0;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -61042,9 +61919,14 @@ var ts;
return ts.visitEachChild(node, visitor, context);
}
function visitYieldExpression(node) {
- if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) {
- var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
- return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
+ if (node.asteriskToken) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ }
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
+ ? ts.visitNode(node.expression, visitor, ts.isExpression)
+ : ts.createVoidZero())), node), node);
}
return ts.visitEachChild(node, visitor, context);
}
@@ -61346,7 +62228,7 @@ var ts;
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
@@ -61371,11 +62253,11 @@ var ts;
statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
}
ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
- var trailingStatements = endLexicalEnvironment();
- if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) {
+ var leadingStatements = endLexicalEnvironment();
+ if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
+ ts.prependRange(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
- ts.addRange(statements, trailingStatements);
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
return body;
@@ -61533,7 +62415,7 @@ var ts;
var asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
- text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
+ text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
context.requestEmitHelper(awaitHelper);
@@ -61550,7 +62432,7 @@ var ts;
var asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
- text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };"
+ text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
context.requestEmitHelper(awaitHelper);
@@ -61561,7 +62443,7 @@ var ts;
var asyncValues = {
name: "typescript:asyncValues",
scoped: false,
- text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };"
+ text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
context.requestEmitHelper(asyncValues);
@@ -61575,7 +62457,7 @@ var ts;
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transform JSX-specific syntax in a SourceFile.
*
@@ -62083,7 +62965,7 @@ var ts;
(function (ts) {
function transformES2016(context) {
var hoistVariableDeclaration = context.hoistVariableDeclaration;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62291,7 +63173,7 @@ var ts;
* be reset.
*/
var enabledSubstitutions;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62467,7 +63349,7 @@ var ts;
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
}
@@ -62721,7 +63603,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -62834,7 +63716,7 @@ var ts;
&& !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
if (constructor) {
prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
@@ -63469,6 +64351,7 @@ var ts;
var expression = ts.visitNode(body, visitor, ts.isExpression);
var returnStatement = ts.createReturn(expression);
ts.setTextRange(returnStatement, body);
+ ts.moveSyntheticComments(returnStatement, body);
ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
statements.push(returnStatement);
// To align with the source map emit for the old emitter, we set a custom
@@ -63476,7 +64359,7 @@ var ts;
closeBraceLocation = body;
}
var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addRange(statements, lexicalEnvironment);
+ ts.prependRange(statements, lexicalEnvironment);
prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
// If we added any final generated statements, this must be a multi-line block
if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) {
@@ -64057,7 +64940,7 @@ var ts;
if (loopOutParameters.length) {
copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4);
}
- ts.addRange(statements_4, lexicalEnvironment);
+ ts.prependRange(statements_4, lexicalEnvironment);
loopBody = ts.createBlock(statements_4, /*multiline*/ true);
}
if (ts.isBlock(loopBody)) {
@@ -64510,10 +65393,12 @@ var ts;
// We skip any outer expressions in a number of places to get to the innermost
// expression, but we will restore them later to preserve comments and source maps.
var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
- // The class statements are the statements generated by visiting the first statement of the
+ // The class statements are the statements generated by visiting the first statement with initializer of the
// body (1), while all other statements are added to remainingStatements (2)
- var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1);
- var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1);
+ var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; };
+ var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
+ var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
+ var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement);
// We know there is only one variable declaration here as we verified this in an
// earlier call to isTypeScriptClassWrapper
@@ -64523,6 +65408,7 @@ var ts;
// we see as an assignment, for example:
//
// (function () {
+ // var C_1;
// var C = C_1 = (function () {
// function C() {
// }
@@ -64531,7 +65417,6 @@ var ts;
// }());
// C = C_1 = __decorate([dec], C);
// return C;
- // var C_1;
// }())
//
var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
@@ -65161,7 +66046,7 @@ var ts;
context.onSubstituteNode = onSubstituteNode;
context.enableSubstitution(184 /* PropertyAccessExpression */);
context.enableSubstitution(269 /* PropertyAssignment */);
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms an ES5 source file to ES3.
*
@@ -65473,7 +66358,7 @@ var ts;
var exceptionBlockStack; // A stack of containing exception blocks.
var currentExceptionBlock; // The current exception block.
var withBlockStack; // A stack containing `with` blocks.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
return node;
@@ -65730,7 +66615,7 @@ var ts;
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -67923,7 +68808,7 @@ var ts;
var currentModuleInfo; // The ExternalModuleInfo for the current file.
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
var needUMDDynamicImportHelper;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -67966,7 +68851,7 @@ var ts;
ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68189,7 +69074,7 @@ var ts;
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68211,7 +69096,7 @@ var ts;
*/
function addExportEqualsIfNeeded(statements, emitAsReturn) {
if (currentModuleInfo.exportEquals) {
- var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor);
+ var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
if (expressionResult) {
if (emitAsReturn) {
var statement = ts.createReturn(expressionResult);
@@ -68252,29 +69137,84 @@ var ts;
return visitFunctionDeclaration(node);
case 234 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 298 /* MergeDeclarationMarker */:
+ case 302 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 303 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
- function importCallExpressionVisitor(node) {
- // This visitor does not need to descend into the tree if there is no dynamic import,
+ function moduleExpressionElementVisitor(node) {
+ // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) {
+ if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
+ else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ return visitDestructuringAssignment(node);
+ }
else {
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
+ function destructuringNeedsFlattening(node) {
+ if (ts.isObjectLiteralExpression(node)) {
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var elem = _a[_i];
+ switch (elem.kind) {
+ case 269 /* PropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.initializer)) {
+ return true;
+ }
+ break;
+ case 270 /* ShorthandPropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.name)) {
+ return true;
+ }
+ break;
+ case 271 /* SpreadAssignment */:
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ break;
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return false;
+ default: ts.Debug.assertNever(elem, "Unhandled object member kind");
+ }
+ }
+ }
+ else if (ts.isArrayLiteralExpression(node)) {
+ for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
+ var elem = _c[_b];
+ if (ts.isSpreadElement(elem)) {
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ }
+ else if (destructuringNeedsFlattening(elem)) {
+ return true;
+ }
+ }
+ }
+ else if (ts.isIdentifier(node)) {
+ return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
+ }
+ return false;
+ }
+ function visitDestructuringAssignment(node) {
+ if (destructuringNeedsFlattening(node.left)) {
+ return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
+ }
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
+ }
function visitImportCallExpression(node) {
- var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor);
+ var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
@@ -68568,10 +69508,10 @@ var ts;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
else {
- statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
return ts.singleOrMany(statements);
}
@@ -68585,13 +69525,13 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor),
- /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)),
+ /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor),
+ /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)),
/*location*/ node),
/*original*/ node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68613,10 +69553,10 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node));
+ /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68661,7 +69601,7 @@ var ts;
}
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68673,6 +69613,21 @@ var ts;
}
return ts.singleOrMany(statements);
}
+ function createAllExportExpressions(name, value, location) {
+ var exportedNames = getExports(name);
+ if (exportedNames) {
+ // For each additional export of the declaration, apply an export assignment.
+ var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
+ for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
+ var exportName = exportedNames_1[_i];
+ // Mark the node to prevent triggering substitution.
+ ts.setEmitFlags(expression, 4 /* NoSubstitution */);
+ expression = createExportExpression(exportName, expression, /*location*/ location);
+ }
+ return expression;
+ }
+ return ts.createAssignment(name, value);
+ }
/**
* Transforms an exported variable with an initializer into an expression.
*
@@ -68680,13 +69635,13 @@ var ts;
*/
function transformInitializedVariable(node) {
if (ts.isBindingPattern(node.name)) {
- return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor),
+ return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor),
/*visitor*/ undefined, context, 0 /* All */,
- /*needsValue*/ false, createExportExpression);
+ /*needsValue*/ false, createAllExportExpressions);
}
else {
return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name),
- /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor));
+ /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor));
}
}
/**
@@ -69090,8 +70045,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
- var exportName = exportedNames_1[_i];
+ for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
+ var exportName = exportedNames_2[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression, /*location*/ node);
@@ -69127,8 +70082,8 @@ var ts;
? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)),
/*location*/ node)
: node;
- for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
- var exportName = exportedNames_2[_i];
+ for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
+ var exportName = exportedNames_3[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression);
@@ -69215,7 +70170,7 @@ var ts;
var hoistedStatements;
var enclosingBlockScopedContainer;
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -69388,7 +70343,7 @@ var ts;
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements);
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -69518,12 +70473,12 @@ var ts;
function createSettersArray(exportStarFunction, dependencyGroups) {
var setters = [];
for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
- var group_2 = dependencyGroups_1[_i];
+ var group_1 = dependencyGroups_1[_i];
// derive a unique name for parameter from the first named entry in the group
- var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
+ var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
var statements = [];
- for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
+ for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) {
var entry = _b[_a];
var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
@@ -70116,9 +71071,9 @@ var ts;
return visitCatchClause(node);
case 212 /* Block */:
return visitBlock(node);
- case 298 /* MergeDeclarationMarker */:
+ case 302 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 303 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -70551,8 +71506,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
- var exportName = exportedNames_3[_i];
+ for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
+ var exportName = exportedNames_4[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
return expression;
@@ -70585,8 +71540,8 @@ var ts;
var expression = node.kind === 198 /* PostfixUnaryExpression */
? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
: node;
- for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
- var exportName = exportedNames_4[_i];
+ for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
+ var exportName = exportedNames_5[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
if (node.kind === 198 /* PostfixUnaryExpression */) {
@@ -70653,7 +71608,7 @@ var ts;
context.enableEmitNotification(273 /* SourceFile */);
context.enableSubstitution(71 /* Identifier */);
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -71160,7 +72115,12 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */;
+ var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
+ 2048 /* WriteClassExpressionAsTypeLiteral */ |
+ 4096 /* UseTypeOfFunction */ |
+ 8 /* UseStructuralFallback */ |
+ 524288 /* AllowEmptyTuple */ |
+ 4 /* GenerateNamesForShadowedTypeParams */;
/**
* Transforms a ts file into a .d.ts file
* This process requires type information, which is retrieved through the emit resolver. Because of this,
@@ -71180,19 +72140,22 @@ var ts;
var lateMarkedStatements;
var lateStatementReplacementMap;
var suppressNewDiagnosticContexts;
+ var host = context.getEmitHost();
var symbolTracker = {
trackSymbol: trackSymbol,
reportInaccessibleThisError: reportInaccessibleThisError,
reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
- reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression
+ reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
+ moduleResolverHost: host,
+ trackReferencedAmbientModule: trackReferencedAmbientModule,
};
var errorNameNode;
var currentSourceFile;
+ var refs;
var resolver = context.getEmitResolver();
var options = context.getCompilerOptions();
var newLine = ts.getNewLineCharacter(options);
var noResolve = options.noResolve, stripInternal = options.stripInternal;
- var host = context.getEmitHost();
return transformRoot;
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
if (!typeReferenceDirectives) {
@@ -71204,6 +72167,10 @@ var ts;
necessaryTypeRefernces.set(ref, true);
}
}
+ function trackReferencedAmbientModule(node) {
+ var container = ts.getSourceFileOfNode(node);
+ refs.set("" + ts.getOriginalNodeId(container), container);
+ }
function handleSymbolAccessibilityError(symbolAccessibilityResult) {
if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
// Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
@@ -71234,6 +72201,8 @@ var ts;
}
}
function trackSymbol(symbol, enclosingDeclaration, meaning) {
+ if (symbol.flags & 262144 /* TypeParameter */)
+ return;
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
@@ -71277,12 +72246,16 @@ var ts;
resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
needsDeclare = false;
var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
return newFile;
}
needsDeclare = true;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ }), ts.mapDefined(node.prepends, function (prepend) {
+ if (prepend.kind === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.declarationText);
+ }
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -71305,13 +72278,13 @@ var ts;
lateMarkedStatements = undefined;
lateStatementReplacementMap = ts.createMap();
necessaryTypeRefernces = undefined;
- var refs = collectReferences(currentSourceFile, ts.createMap());
+ refs = collectReferences(currentSourceFile, ts.createMap());
var references = [];
var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
- refs.forEach(referenceVisitor);
var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
- var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements);
+ var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
+ refs.forEach(referenceVisitor);
var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements);
@@ -71323,17 +72296,19 @@ var ts;
}
function getFileReferenceForTypeName(typeName) {
// Elide type references for which we have imports
- for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
- var importStatement = emittedImports_1[_i];
- if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
- var expr = importStatement.moduleReference.expression;
- if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
+ if (emittedImports) {
+ for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
+ var importStatement = emittedImports_1[_i];
+ if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
+ var expr = importStatement.moduleReference.expression;
+ if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
+ return undefined;
+ }
+ }
+ else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
return undefined;
}
}
- else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
- return undefined;
- }
}
return { fileName: typeName, pos: -1, end: -1 };
}
@@ -71366,7 +72341,7 @@ var ts;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
if (elem) {
- ret.set("" + ts.getNodeId(elem), elem);
+ ret.set("" + ts.getOriginalNodeId(elem), elem);
}
});
return ret;
@@ -71583,7 +72558,7 @@ var ts;
}
// Nothing visible
}
- function filterCandidateImports(statements) {
+ function transformAndReplaceLatePaintedStatements(statements) {
// This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
// error handling which must now be included in the output and themselves checked for errors.
// For example:
@@ -71598,62 +72573,45 @@ var ts;
// In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
// be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
// dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
- var unconsideredStatements = [];
while (ts.length(lateMarkedStatements)) {
var i = lateMarkedStatements.shift();
- if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope
- unconsideredStatements.push(i);
- continue;
- }
if (!ts.isLateVisibilityPaintedStatement(i)) {
- return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
- }
- switch (i.kind) {
- case 242 /* ImportEqualsDeclaration */: {
- var result = transformImportEqualsDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 243 /* ImportDeclaration */: {
- var result = transformImportDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 213 /* VariableStatement */: {
- var result = transformVariableStatement(i, /*privateDeclaration*/ true); // Transform the statement (potentially again, possibly revealing more sub-nodes)
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- default: ts.Debug.assertNever(i, "Unhandled late painted statement!");
+ return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
}
+ var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true);
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
}
- // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not
- // be considered in the child scope
- lateMarkedStatements = unconsideredStatements;
// And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
// (and remove them from the set to examine for outter declarations)
return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
- }
- function visitLateVisibilityMarkedStatements(statement) {
- if (ts.isLateVisibilityPaintedStatement(statement)) {
- var key = "" + ts.getNodeId(statement);
- if (lateStatementReplacementMap.has(key)) {
- var result = lateStatementReplacementMap.get(key);
- lateStatementReplacementMap.delete(key);
- if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */)) {
- // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
- needsScopeFixMarker = true;
+ function visitLateVisibilityMarkedStatements(statement) {
+ if (ts.isLateVisibilityPaintedStatement(statement)) {
+ var key = "" + ts.getOriginalNodeId(statement);
+ if (lateStatementReplacementMap.has(key)) {
+ var result = lateStatementReplacementMap.get(key);
+ lateStatementReplacementMap.delete(key);
+ if (result && ts.isSourceFile(statement.parent)) {
+ if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) {
+ // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
+ needsScopeFixMarker = true;
+ }
+ if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) {
+ resultHasExternalModuleIndicator = true;
+ }
+ }
+ return result;
}
- return result;
}
- else {
- return ts.getParseTreeNode(statement) ? undefined : statement;
- }
- }
- else {
return statement;
}
}
+ function isExternalModuleIndicator(result) {
+ // Exported top-level member indicates moduleness
+ return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
+ }
+ function needsScopeMarker(result) {
+ return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
+ }
function visitDeclarationSubtree(input) {
if (shouldStripInternal(input))
return;
@@ -71851,13 +72809,21 @@ var ts;
return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
}
}
- case 242 /* ImportEqualsDeclaration */:
+ }
+ var result = transformTopLevelDeclaration(input);
+ // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
+ return input;
+ }
+ function transformTopLevelDeclaration(input, isPrivate) {
+ if (shouldStripInternal(input))
+ return;
+ switch (input.kind) {
+ case 242 /* ImportEqualsDeclaration */: {
+ return transformImportEqualsDeclaration(input);
+ }
case 243 /* ImportDeclaration */: {
- // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later
- // to reduce the likelihood we need to rewrite it
- lateMarkedStatements = lateMarkedStatements || [];
- ts.pushIfUnique(lateMarkedStatements, input);
- return input;
+ return transformImportDeclaration(input);
}
}
if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
@@ -71870,52 +72836,53 @@ var ts;
previousEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = input;
}
- var previousNeedsDeclare;
var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
var oldDiag = getSymbolAccessibilityDiagnostic;
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
}
- var oldPossibleImports;
+ var previousNeedsDeclare = needsDeclare;
switch (input.kind) {
case 236 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
return cleanup(ts.updateTypeAliasDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
case 235 /* InterfaceDeclaration */: {
return cleanup(ts.updateInterfaceDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
}
case 233 /* FunctionDeclaration */: {
// Generators lose their generator-ness, excepting their return type
return cleanup(ts.updateFunctionDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input),
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate),
/*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
/*body*/ undefined));
}
case 238 /* ModuleDeclaration */: {
- previousNeedsDeclare = needsDeclare;
needsDeclare = false;
- oldPossibleImports = lateMarkedStatements;
- lateMarkedStatements = undefined;
var inner = input.body;
if (inner && inner.kind === 239 /* ModuleBlock */) {
var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
- var body = ts.updateModuleBlock(inner, filterCandidateImports(statements));
+ var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements));
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
return cleanup(ts.updateModuleDeclaration(input,
/*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
}
else {
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
needsDeclare = false;
+ ts.visitNode(inner, visitDeclarationStatements);
+ // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
+ var id = "" + ts.getOriginalNodeId(inner);
+ var body = lateStatementReplacementMap.get(id);
+ lateStatementReplacementMap.delete(id);
return cleanup(ts.updateModuleDeclaration(input,
- /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements)));
+ /*decorators*/ undefined, mods, input.name, body));
}
}
case 234 /* ClassDeclaration */: {
- var modifiers = ts.createNodeArray(ensureModifiers(input));
+ var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate));
var typeParameters = ensureTypeParams(input, input.typeParameters);
var ctor = ts.getFirstConstructorWithBody(input);
var parameterProperties = void 0;
@@ -71985,12 +72952,10 @@ var ts;
}
}
case 213 /* VariableStatement */: {
- var result = transformVariableStatement(input);
- lateStatementReplacementMap.set("" + ts.getNodeId(input), result); // Don't actually elide yet; just leave as original node - will be elided/swapped by late pass
- return cleanup(input);
+ return cleanup(transformVariableStatement(input, isPrivate));
}
case 237 /* EnumDeclaration */: {
- return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
+ return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
if (shouldStripInternal(m))
return;
// Rewrite enum values to their constants, if available
@@ -72001,27 +72966,20 @@ var ts;
}
// Anything left unhandled is an error, so this should be unreachable
return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
- function cleanup(returnValue) {
+ function cleanup(node) {
if (isEnclosingDeclaration(input)) {
enclosingDeclaration = previousEnclosingDeclaration;
}
- if (input.kind === 238 /* ModuleDeclaration */) {
- needsDeclare = previousNeedsDeclare;
- lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements);
- }
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = oldDiag;
}
- if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) {
- if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) {
- // Exported top-level member indicates moduleness
- resultHasExternalModuleIndicator = true;
- }
+ if (input.kind === 238 /* ModuleDeclaration */) {
+ needsDeclare = previousNeedsDeclare;
}
- if (returnValue === input) {
- return returnValue;
+ if (node === input) {
+ return node;
}
- return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
+ return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
}
}
function transformVariableStatement(input, privateDeclaration) {
@@ -72098,7 +73056,7 @@ var ts;
return maskModifierFlags(node, mask, additions);
}
function ensureAccessor(node) {
- var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
+ var accessors = resolver.getAllAccessorDeclarations(node);
if (node.kind !== accessors.firstAccessor.kind) {
return;
}
@@ -72111,7 +73069,7 @@ var ts;
var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined);
var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile);
if (leadingsSyntheticCommentRanges) {
- var _loop_8 = function (range) {
+ var _loop_9 = function (range) {
if (range.kind === 3 /* MultiLineCommentTrivia */) {
var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2);
var lines = text.split(/\r\n?|\n/g);
@@ -72125,7 +73083,7 @@ var ts;
};
for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) {
var range = leadingsSyntheticCommentRanges_1[_i];
- _loop_8(range);
+ _loop_9(range);
}
}
return prop;
@@ -72287,7 +73245,7 @@ var ts;
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(300 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(304 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -72782,7 +73740,7 @@ var ts;
source = undefined;
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 299 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitPos(skipSourceTrivia(pos));
@@ -72799,7 +73757,7 @@ var ts;
}
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 299 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitPos(end);
@@ -72975,7 +73933,7 @@ var ts;
if (extendedDiagnostics) {
ts.performance.mark("preEmitNodeWithComment");
}
- var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 299 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */;
@@ -73299,6 +74257,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
+ var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
/*@internal*/
/**
@@ -73315,7 +74274,7 @@ var ts;
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles);
+ var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -73341,7 +74300,8 @@ var ts;
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
}
else {
var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options));
@@ -73350,17 +74310,27 @@ var ts;
var isJs = ts.isSourceFileJavaScript(sourceFile);
var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
+ function createDefaultBundleInfo() {
+ return {
+ originalOffset: -1,
+ totalLength: -1
+ };
+ }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
+ /* @internal */
function getOutputExtension(sourceFile, options) {
+ if (ts.isJsonSourceFile(sourceFile)) {
+ return ".json" /* Json */;
+ }
if (options.jsx === 1 /* Preserve */) {
if (ts.isSourceFileJavaScript(sourceFile)) {
if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
@@ -73374,9 +74344,10 @@ var ts;
}
return ".js" /* Js */;
}
+ ts.getOutputExtension = getOutputExtension;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -73390,6 +74361,7 @@ var ts;
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
+ var bundleInfo = createDefaultBundleInfo();
var emitSkipped = false;
// Emit each output file
ts.performance.mark("beforePrint");
@@ -73402,8 +74374,8 @@ var ts;
sourceMaps: sourceMapDataList
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
@@ -73415,10 +74387,12 @@ var ts;
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
+ if (bundleInfoPath) {
+ emittedFilesList.push(bundleInfoPath);
+ }
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
- var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
// Make sure not to write js file and source map file if any of them cannot be written
if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) {
emitSkipped = true;
@@ -73428,7 +74402,7 @@ var ts;
return;
}
// Transform the source files
- var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false);
+ var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false);
// Create a printer to print the nodes
var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), {
// resolver hooks
@@ -73443,7 +74417,8 @@ var ts;
// emitter hooks
onSetSourceFile: setSourceFile,
});
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap);
+ ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap);
// Clean up emit nodes on parse tree
transform.dispose();
}
@@ -73454,8 +74429,8 @@ var ts;
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
// Setup and perform the transformation to retrieve declarations from the input files
var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript);
- var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles;
- var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false);
+ var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
+ var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false);
if (ts.length(declarationTransform.diagnostics)) {
for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
var diagnostic = _b[_a];
@@ -73477,17 +74452,18 @@ var ts;
var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap);
+ ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap);
}
declarationTransform.dispose();
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) {
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) {
var bundle = sourceFileOrBundle.kind === 274 /* Bundle */ ? sourceFileOrBundle : undefined;
var sourceFile = sourceFileOrBundle.kind === 273 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList);
if (bundle) {
- printer.writeBundle(bundle, writer);
+ printer.writeBundle(bundle, writer, bundleInfo);
}
else {
printer.writeFile(sourceFile, writer);
@@ -73503,9 +74479,15 @@ var ts;
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles);
+ // Write bundled offset information if applicable
+ if (bundleInfoPath) {
+ bundleInfo.totalLength = writer.getTextPos();
+ ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
+ }
// Reset state
mapRecorder.reset();
writer.clear();
+ bundleInfo = createDefaultBundleInfo();
}
function setSourceFile(node) {
sourceMap.setSourceFile(node);
@@ -73515,6 +74497,13 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ var PipelinePhase;
+ (function (PipelinePhase) {
+ PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
+ PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments";
+ PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps";
+ PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit";
+ })(PipelinePhase || (PipelinePhase = {}));
function createPrinter(printerOptions, handlers) {
if (printerOptions === void 0) { printerOptions = {}; }
if (handlers === void 0) { handlers = {}; }
@@ -73572,6 +74561,7 @@ var ts;
switch (node.kind) {
case 273 /* SourceFile */: return printFile(node);
case 274 /* Bundle */: return printBundle(node);
+ case 275 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -73588,6 +74578,10 @@ var ts;
writeFile(sourceFile, beginPrint());
return endPrint();
}
+ function printUnparsedSource(unparsed) {
+ writeUnparsedSource(unparsed, beginPrint());
+ return endPrint();
+ }
function writeNode(hint, node, sourceFile, output) {
var previousWriter = writer;
setWriter(output);
@@ -73605,7 +74599,7 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, output) {
+ function writeBundle(bundle, output, bundleInfo) {
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output);
@@ -73613,13 +74607,28 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ writeLine();
+ }
+ if (bundleInfo) {
+ bundleInfo.originalOffset = writer.getTextPos();
+ }
+ for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
reset();
writer = previousWriter;
}
+ function writeUnparsedSource(unparsed, output) {
+ var previousWriter = writer;
+ setWriter(output);
+ print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
+ reset();
+ writer = previousWriter;
+ }
function writeFile(sourceFile, output) {
isOwnFileEmit = true;
var previousWriter = writer;
@@ -73642,7 +74651,8 @@ var ts;
if (sourceFile) {
setSourceFile(sourceFile);
}
- pipelineEmitWithNotification(hint, node);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, hint);
+ pipelinePhase(hint, node);
}
function setSourceFile(sourceFile) {
currentSourceFile = sourceFile;
@@ -73665,417 +74675,422 @@ var ts;
comments.reset();
setWriter(/*output*/ undefined);
}
- // TODO: Should this just be `emit`?
- // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034
- function emitIfPresent(node) {
- if (node) {
- emit(node);
- }
- }
function emit(node) {
- pipelineEmitWithNotification(4 /* Unspecified */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */);
+ pipelinePhase(4 /* Unspecified */, node);
}
function emitIdentifierName(node) {
- pipelineEmitWithNotification(2 /* IdentifierName */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */);
+ pipelinePhase(2 /* IdentifierName */, node);
}
function emitExpression(node) {
- pipelineEmitWithNotification(1 /* Expression */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */);
+ pipelinePhase(1 /* Expression */, node);
+ }
+ function getPipelinePhase(phase, hint) {
+ switch (phase) {
+ case 0 /* Notification */:
+ if (onEmitNode) {
+ return pipelineEmitWithNotification;
+ }
+ // falls through
+ case 1 /* Comments */:
+ if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
+ return pipelineEmitWithComments;
+ }
+ return pipelineEmitWithoutComments;
+ case 2 /* SourceMaps */:
+ if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
+ return pipelineEmitWithSourceMap;
+ }
+ // falls through
+ case 3 /* Emit */:
+ return pipelineEmitWithHint;
+ default:
+ return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase);
+ }
+ }
+ function getNextPipelinePhase(currentPhase, hint) {
+ return getPipelinePhase(currentPhase + 1, hint);
}
function pipelineEmitWithNotification(hint, node) {
- if (onEmitNode) {
- onEmitNode(hint, node, pipelineEmitWithComments);
- }
- else {
- pipelineEmitWithComments(hint, node);
- }
+ ts.Debug.assertDefined(onEmitNode);
+ onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint));
}
function pipelineEmitWithComments(hint, node) {
- node = trySubstituteNode(hint, node);
- if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
- emitNodeWithComments(hint, node, pipelineEmitWithSourceMap);
- }
- else {
- pipelineEmitWithSourceMap(hint, node);
- }
+ ts.Debug.assertDefined(emitNodeWithComments);
+ ts.Debug.assert(hint !== 0 /* SourceFile */);
+ emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint));
+ }
+ function pipelineEmitWithoutComments(hint, node) {
+ var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint);
+ pipelinePhase(hint, trySubstituteNode(hint, node));
}
function pipelineEmitWithSourceMap(hint, node) {
- if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
- onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
- }
- else {
- pipelineEmitWithHint(hint, node);
- }
+ ts.Debug.assertDefined(onEmitSourceMapOfNode);
+ ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */);
+ onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
}
function pipelineEmitWithHint(hint, node) {
- switch (hint) {
- case 0 /* SourceFile */: return pipelineEmitSourceFile(node);
- case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node);
- case 1 /* Expression */: return pipelineEmitExpression(node);
- case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
- case 4 /* Unspecified */: return pipelineEmitUnspecified(node);
+ if (hint === 0 /* SourceFile */)
+ return emitSourceFile(ts.cast(node, ts.isSourceFile));
+ if (hint === 2 /* IdentifierName */)
+ return emitIdentifier(ts.cast(node, ts.isIdentifier));
+ if (hint === 3 /* MappedTypeParameter */)
+ return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
+ if (hint === 4 /* Unspecified */) {
+ if (ts.isKeyword(node.kind))
+ return writeTokenNode(node, writeKeyword);
+ switch (node.kind) {
+ // Pseudo-literals
+ case 14 /* TemplateHead */:
+ case 15 /* TemplateMiddle */:
+ case 16 /* TemplateTail */:
+ return emitLiteral(node);
+ case 275 /* UnparsedSource */:
+ return emitUnparsedSource(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Parse tree nodes
+ // Names
+ case 145 /* QualifiedName */:
+ return emitQualifiedName(node);
+ case 146 /* ComputedPropertyName */:
+ return emitComputedPropertyName(node);
+ // Signature elements
+ case 147 /* TypeParameter */:
+ return emitTypeParameter(node);
+ case 148 /* Parameter */:
+ return emitParameter(node);
+ case 149 /* Decorator */:
+ return emitDecorator(node);
+ // Type members
+ case 150 /* PropertySignature */:
+ return emitPropertySignature(node);
+ case 151 /* PropertyDeclaration */:
+ return emitPropertyDeclaration(node);
+ case 152 /* MethodSignature */:
+ return emitMethodSignature(node);
+ case 153 /* MethodDeclaration */:
+ return emitMethodDeclaration(node);
+ case 154 /* Constructor */:
+ return emitConstructor(node);
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return emitAccessorDeclaration(node);
+ case 157 /* CallSignature */:
+ return emitCallSignature(node);
+ case 158 /* ConstructSignature */:
+ return emitConstructSignature(node);
+ case 159 /* IndexSignature */:
+ return emitIndexSignature(node);
+ // Types
+ case 160 /* TypePredicate */:
+ return emitTypePredicate(node);
+ case 161 /* TypeReference */:
+ return emitTypeReference(node);
+ case 162 /* FunctionType */:
+ return emitFunctionType(node);
+ case 283 /* JSDocFunctionType */:
+ return emitJSDocFunctionType(node);
+ case 163 /* ConstructorType */:
+ return emitConstructorType(node);
+ case 164 /* TypeQuery */:
+ return emitTypeQuery(node);
+ case 165 /* TypeLiteral */:
+ return emitTypeLiteral(node);
+ case 166 /* ArrayType */:
+ return emitArrayType(node);
+ case 167 /* TupleType */:
+ return emitTupleType(node);
+ case 168 /* UnionType */:
+ return emitUnionType(node);
+ case 169 /* IntersectionType */:
+ return emitIntersectionType(node);
+ case 170 /* ConditionalType */:
+ return emitConditionalType(node);
+ case 171 /* InferType */:
+ return emitInferType(node);
+ case 172 /* ParenthesizedType */:
+ return emitParenthesizedType(node);
+ case 206 /* ExpressionWithTypeArguments */:
+ return emitExpressionWithTypeArguments(node);
+ case 173 /* ThisType */:
+ return emitThisType();
+ case 174 /* TypeOperator */:
+ return emitTypeOperator(node);
+ case 175 /* IndexedAccessType */:
+ return emitIndexedAccessType(node);
+ case 176 /* MappedType */:
+ return emitMappedType(node);
+ case 177 /* LiteralType */:
+ return emitLiteralType(node);
+ case 178 /* ImportType */:
+ return emitImportTypeNode(node);
+ case 278 /* JSDocAllType */:
+ write("*");
+ return;
+ case 279 /* JSDocUnknownType */:
+ write("?");
+ return;
+ case 280 /* JSDocNullableType */:
+ return emitJSDocNullableType(node);
+ case 281 /* JSDocNonNullableType */:
+ return emitJSDocNonNullableType(node);
+ case 282 /* JSDocOptionalType */:
+ return emitJSDocOptionalType(node);
+ case 284 /* JSDocVariadicType */:
+ return emitJSDocVariadicType(node);
+ // Binding patterns
+ case 179 /* ObjectBindingPattern */:
+ return emitObjectBindingPattern(node);
+ case 180 /* ArrayBindingPattern */:
+ return emitArrayBindingPattern(node);
+ case 181 /* BindingElement */:
+ return emitBindingElement(node);
+ // Misc
+ case 210 /* TemplateSpan */:
+ return emitTemplateSpan(node);
+ case 211 /* SemicolonClassElement */:
+ return emitSemicolonClassElement();
+ // Statements
+ case 212 /* Block */:
+ return emitBlock(node);
+ case 213 /* VariableStatement */:
+ return emitVariableStatement(node);
+ case 214 /* EmptyStatement */:
+ return emitEmptyStatement();
+ case 215 /* ExpressionStatement */:
+ return emitExpressionStatement(node);
+ case 216 /* IfStatement */:
+ return emitIfStatement(node);
+ case 217 /* DoStatement */:
+ return emitDoStatement(node);
+ case 218 /* WhileStatement */:
+ return emitWhileStatement(node);
+ case 219 /* ForStatement */:
+ return emitForStatement(node);
+ case 220 /* ForInStatement */:
+ return emitForInStatement(node);
+ case 221 /* ForOfStatement */:
+ return emitForOfStatement(node);
+ case 222 /* ContinueStatement */:
+ return emitContinueStatement(node);
+ case 223 /* BreakStatement */:
+ return emitBreakStatement(node);
+ case 224 /* ReturnStatement */:
+ return emitReturnStatement(node);
+ case 225 /* WithStatement */:
+ return emitWithStatement(node);
+ case 226 /* SwitchStatement */:
+ return emitSwitchStatement(node);
+ case 227 /* LabeledStatement */:
+ return emitLabeledStatement(node);
+ case 228 /* ThrowStatement */:
+ return emitThrowStatement(node);
+ case 229 /* TryStatement */:
+ return emitTryStatement(node);
+ case 230 /* DebuggerStatement */:
+ return emitDebuggerStatement(node);
+ // Declarations
+ case 231 /* VariableDeclaration */:
+ return emitVariableDeclaration(node);
+ case 232 /* VariableDeclarationList */:
+ return emitVariableDeclarationList(node);
+ case 233 /* FunctionDeclaration */:
+ return emitFunctionDeclaration(node);
+ case 234 /* ClassDeclaration */:
+ return emitClassDeclaration(node);
+ case 235 /* InterfaceDeclaration */:
+ return emitInterfaceDeclaration(node);
+ case 236 /* TypeAliasDeclaration */:
+ return emitTypeAliasDeclaration(node);
+ case 237 /* EnumDeclaration */:
+ return emitEnumDeclaration(node);
+ case 238 /* ModuleDeclaration */:
+ return emitModuleDeclaration(node);
+ case 239 /* ModuleBlock */:
+ return emitModuleBlock(node);
+ case 240 /* CaseBlock */:
+ return emitCaseBlock(node);
+ case 241 /* NamespaceExportDeclaration */:
+ return emitNamespaceExportDeclaration(node);
+ case 242 /* ImportEqualsDeclaration */:
+ return emitImportEqualsDeclaration(node);
+ case 243 /* ImportDeclaration */:
+ return emitImportDeclaration(node);
+ case 244 /* ImportClause */:
+ return emitImportClause(node);
+ case 245 /* NamespaceImport */:
+ return emitNamespaceImport(node);
+ case 246 /* NamedImports */:
+ return emitNamedImports(node);
+ case 247 /* ImportSpecifier */:
+ return emitImportSpecifier(node);
+ case 248 /* ExportAssignment */:
+ return emitExportAssignment(node);
+ case 249 /* ExportDeclaration */:
+ return emitExportDeclaration(node);
+ case 250 /* NamedExports */:
+ return emitNamedExports(node);
+ case 251 /* ExportSpecifier */:
+ return emitExportSpecifier(node);
+ case 252 /* MissingDeclaration */:
+ return;
+ // Module references
+ case 253 /* ExternalModuleReference */:
+ return emitExternalModuleReference(node);
+ // JSX (non-expression)
+ case 10 /* JsxText */:
+ return emitJsxText(node);
+ case 256 /* JsxOpeningElement */:
+ case 259 /* JsxOpeningFragment */:
+ return emitJsxOpeningElementOrFragment(node);
+ case 257 /* JsxClosingElement */:
+ case 260 /* JsxClosingFragment */:
+ return emitJsxClosingElementOrFragment(node);
+ case 261 /* JsxAttribute */:
+ return emitJsxAttribute(node);
+ case 262 /* JsxAttributes */:
+ return emitJsxAttributes(node);
+ case 263 /* JsxSpreadAttribute */:
+ return emitJsxSpreadAttribute(node);
+ case 264 /* JsxExpression */:
+ return emitJsxExpression(node);
+ // Clauses
+ case 265 /* CaseClause */:
+ return emitCaseClause(node);
+ case 266 /* DefaultClause */:
+ return emitDefaultClause(node);
+ case 267 /* HeritageClause */:
+ return emitHeritageClause(node);
+ case 268 /* CatchClause */:
+ return emitCatchClause(node);
+ // Property assignments
+ case 269 /* PropertyAssignment */:
+ return emitPropertyAssignment(node);
+ case 270 /* ShorthandPropertyAssignment */:
+ return emitShorthandPropertyAssignment(node);
+ case 271 /* SpreadAssignment */:
+ return emitSpreadAssignment(node);
+ // Enum
+ case 272 /* EnumMember */:
+ return emitEnumMember(node);
+ // JSDoc nodes (ignored)
+ // Transformation nodes (ignored)
+ }
+ if (ts.isExpression(node)) {
+ hint = 1 /* Expression */;
+ node = trySubstituteNode(1 /* Expression */, node);
+ }
+ else if (ts.isToken(node)) {
+ return writeTokenNode(node, writePunctuation);
+ }
+ }
+ if (hint === 1 /* Expression */) {
+ switch (node.kind) {
+ // Literals
+ case 8 /* NumericLiteral */:
+ return emitNumericLiteral(node);
+ case 9 /* StringLiteral */:
+ case 12 /* RegularExpressionLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ return emitLiteral(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Reserved words
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ case 97 /* SuperKeyword */:
+ case 101 /* TrueKeyword */:
+ case 99 /* ThisKeyword */:
+ case 91 /* ImportKeyword */:
+ writeTokenNode(node, writeKeyword);
+ return;
+ // Expressions
+ case 182 /* ArrayLiteralExpression */:
+ return emitArrayLiteralExpression(node);
+ case 183 /* ObjectLiteralExpression */:
+ return emitObjectLiteralExpression(node);
+ case 184 /* PropertyAccessExpression */:
+ return emitPropertyAccessExpression(node);
+ case 185 /* ElementAccessExpression */:
+ return emitElementAccessExpression(node);
+ case 186 /* CallExpression */:
+ return emitCallExpression(node);
+ case 187 /* NewExpression */:
+ return emitNewExpression(node);
+ case 188 /* TaggedTemplateExpression */:
+ return emitTaggedTemplateExpression(node);
+ case 189 /* TypeAssertionExpression */:
+ return emitTypeAssertionExpression(node);
+ case 190 /* ParenthesizedExpression */:
+ return emitParenthesizedExpression(node);
+ case 191 /* FunctionExpression */:
+ return emitFunctionExpression(node);
+ case 192 /* ArrowFunction */:
+ return emitArrowFunction(node);
+ case 193 /* DeleteExpression */:
+ return emitDeleteExpression(node);
+ case 194 /* TypeOfExpression */:
+ return emitTypeOfExpression(node);
+ case 195 /* VoidExpression */:
+ return emitVoidExpression(node);
+ case 196 /* AwaitExpression */:
+ return emitAwaitExpression(node);
+ case 197 /* PrefixUnaryExpression */:
+ return emitPrefixUnaryExpression(node);
+ case 198 /* PostfixUnaryExpression */:
+ return emitPostfixUnaryExpression(node);
+ case 199 /* BinaryExpression */:
+ return emitBinaryExpression(node);
+ case 200 /* ConditionalExpression */:
+ return emitConditionalExpression(node);
+ case 201 /* TemplateExpression */:
+ return emitTemplateExpression(node);
+ case 202 /* YieldExpression */:
+ return emitYieldExpression(node);
+ case 203 /* SpreadElement */:
+ return emitSpreadExpression(node);
+ case 204 /* ClassExpression */:
+ return emitClassExpression(node);
+ case 205 /* OmittedExpression */:
+ return;
+ case 207 /* AsExpression */:
+ return emitAsExpression(node);
+ case 208 /* NonNullExpression */:
+ return emitNonNullExpression(node);
+ case 209 /* MetaProperty */:
+ return emitMetaProperty(node);
+ // JSX
+ case 254 /* JsxElement */:
+ return emitJsxElement(node);
+ case 255 /* JsxSelfClosingElement */:
+ return emitJsxSelfClosingElement(node);
+ case 258 /* JsxFragment */:
+ return emitJsxFragment(node);
+ // Transformation nodes
+ case 300 /* PartiallyEmittedExpression */:
+ return emitPartiallyEmittedExpression(node);
+ case 301 /* CommaListExpression */:
+ return emitCommaList(node);
+ }
}
- }
- function pipelineEmitSourceFile(node) {
- ts.Debug.assertNode(node, ts.isSourceFile);
- emitSourceFile(node);
- }
- function pipelineEmitIdentifierName(node) {
- ts.Debug.assertNode(node, ts.isIdentifier);
- emitIdentifier(node);
}
function emitMappedTypeParameter(node) {
emit(node.name);
writeSpace();
writeKeyword("in");
writeSpace();
- emitIfPresent(node.constraint);
- }
- function pipelineEmitUnspecified(node) {
- var kind = node.kind;
- // Reserved words
- // Strict mode reserved words
- // Contextual keywords
- if (ts.isKeyword(kind)) {
- writeTokenNode(node, writeKeyword);
- return;
- }
- switch (kind) {
- // Pseudo-literals
- case 14 /* TemplateHead */:
- case 15 /* TemplateMiddle */:
- case 16 /* TemplateTail */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Parse tree nodes
- // Names
- case 145 /* QualifiedName */:
- return emitQualifiedName(node);
- case 146 /* ComputedPropertyName */:
- return emitComputedPropertyName(node);
- // Signature elements
- case 147 /* TypeParameter */:
- return emitTypeParameter(node);
- case 148 /* Parameter */:
- return emitParameter(node);
- case 149 /* Decorator */:
- return emitDecorator(node);
- // Type members
- case 150 /* PropertySignature */:
- return emitPropertySignature(node);
- case 151 /* PropertyDeclaration */:
- return emitPropertyDeclaration(node);
- case 152 /* MethodSignature */:
- return emitMethodSignature(node);
- case 153 /* MethodDeclaration */:
- return emitMethodDeclaration(node);
- case 154 /* Constructor */:
- return emitConstructor(node);
- case 155 /* GetAccessor */:
- case 156 /* SetAccessor */:
- return emitAccessorDeclaration(node);
- case 157 /* CallSignature */:
- return emitCallSignature(node);
- case 158 /* ConstructSignature */:
- return emitConstructSignature(node);
- case 159 /* IndexSignature */:
- return emitIndexSignature(node);
- // Types
- case 160 /* TypePredicate */:
- return emitTypePredicate(node);
- case 161 /* TypeReference */:
- return emitTypeReference(node);
- case 162 /* FunctionType */:
- return emitFunctionType(node);
- case 281 /* JSDocFunctionType */:
- return emitJSDocFunctionType(node);
- case 163 /* ConstructorType */:
- return emitConstructorType(node);
- case 164 /* TypeQuery */:
- return emitTypeQuery(node);
- case 165 /* TypeLiteral */:
- return emitTypeLiteral(node);
- case 166 /* ArrayType */:
- return emitArrayType(node);
- case 167 /* TupleType */:
- return emitTupleType(node);
- case 168 /* UnionType */:
- return emitUnionType(node);
- case 169 /* IntersectionType */:
- return emitIntersectionType(node);
- case 170 /* ConditionalType */:
- return emitConditionalType(node);
- case 171 /* InferType */:
- return emitInferType(node);
- case 172 /* ParenthesizedType */:
- return emitParenthesizedType(node);
- case 206 /* ExpressionWithTypeArguments */:
- return emitExpressionWithTypeArguments(node);
- case 173 /* ThisType */:
- return emitThisType();
- case 174 /* TypeOperator */:
- return emitTypeOperator(node);
- case 175 /* IndexedAccessType */:
- return emitIndexedAccessType(node);
- case 176 /* MappedType */:
- return emitMappedType(node);
- case 177 /* LiteralType */:
- return emitLiteralType(node);
- case 178 /* ImportType */:
- return emitImportTypeNode(node);
- case 276 /* JSDocAllType */:
- write("*");
- return;
- case 277 /* JSDocUnknownType */:
- write("?");
- return;
- case 278 /* JSDocNullableType */:
- return emitJSDocNullableType(node);
- case 279 /* JSDocNonNullableType */:
- return emitJSDocNonNullableType(node);
- case 280 /* JSDocOptionalType */:
- return emitJSDocOptionalType(node);
- case 282 /* JSDocVariadicType */:
- return emitJSDocVariadicType(node);
- // Binding patterns
- case 179 /* ObjectBindingPattern */:
- return emitObjectBindingPattern(node);
- case 180 /* ArrayBindingPattern */:
- return emitArrayBindingPattern(node);
- case 181 /* BindingElement */:
- return emitBindingElement(node);
- // Misc
- case 210 /* TemplateSpan */:
- return emitTemplateSpan(node);
- case 211 /* SemicolonClassElement */:
- return emitSemicolonClassElement();
- // Statements
- case 212 /* Block */:
- return emitBlock(node);
- case 213 /* VariableStatement */:
- return emitVariableStatement(node);
- case 214 /* EmptyStatement */:
- return emitEmptyStatement();
- case 215 /* ExpressionStatement */:
- return emitExpressionStatement(node);
- case 216 /* IfStatement */:
- return emitIfStatement(node);
- case 217 /* DoStatement */:
- return emitDoStatement(node);
- case 218 /* WhileStatement */:
- return emitWhileStatement(node);
- case 219 /* ForStatement */:
- return emitForStatement(node);
- case 220 /* ForInStatement */:
- return emitForInStatement(node);
- case 221 /* ForOfStatement */:
- return emitForOfStatement(node);
- case 222 /* ContinueStatement */:
- return emitContinueStatement(node);
- case 223 /* BreakStatement */:
- return emitBreakStatement(node);
- case 224 /* ReturnStatement */:
- return emitReturnStatement(node);
- case 225 /* WithStatement */:
- return emitWithStatement(node);
- case 226 /* SwitchStatement */:
- return emitSwitchStatement(node);
- case 227 /* LabeledStatement */:
- return emitLabeledStatement(node);
- case 228 /* ThrowStatement */:
- return emitThrowStatement(node);
- case 229 /* TryStatement */:
- return emitTryStatement(node);
- case 230 /* DebuggerStatement */:
- return emitDebuggerStatement(node);
- // Declarations
- case 231 /* VariableDeclaration */:
- return emitVariableDeclaration(node);
- case 232 /* VariableDeclarationList */:
- return emitVariableDeclarationList(node);
- case 233 /* FunctionDeclaration */:
- return emitFunctionDeclaration(node);
- case 234 /* ClassDeclaration */:
- return emitClassDeclaration(node);
- case 235 /* InterfaceDeclaration */:
- return emitInterfaceDeclaration(node);
- case 236 /* TypeAliasDeclaration */:
- return emitTypeAliasDeclaration(node);
- case 237 /* EnumDeclaration */:
- return emitEnumDeclaration(node);
- case 238 /* ModuleDeclaration */:
- return emitModuleDeclaration(node);
- case 239 /* ModuleBlock */:
- return emitModuleBlock(node);
- case 240 /* CaseBlock */:
- return emitCaseBlock(node);
- case 241 /* NamespaceExportDeclaration */:
- return emitNamespaceExportDeclaration(node);
- case 242 /* ImportEqualsDeclaration */:
- return emitImportEqualsDeclaration(node);
- case 243 /* ImportDeclaration */:
- return emitImportDeclaration(node);
- case 244 /* ImportClause */:
- return emitImportClause(node);
- case 245 /* NamespaceImport */:
- return emitNamespaceImport(node);
- case 246 /* NamedImports */:
- return emitNamedImports(node);
- case 247 /* ImportSpecifier */:
- return emitImportSpecifier(node);
- case 248 /* ExportAssignment */:
- return emitExportAssignment(node);
- case 249 /* ExportDeclaration */:
- return emitExportDeclaration(node);
- case 250 /* NamedExports */:
- return emitNamedExports(node);
- case 251 /* ExportSpecifier */:
- return emitExportSpecifier(node);
- case 252 /* MissingDeclaration */:
- return;
- // Module references
- case 253 /* ExternalModuleReference */:
- return emitExternalModuleReference(node);
- // JSX (non-expression)
- case 10 /* JsxText */:
- return emitJsxText(node);
- case 256 /* JsxOpeningElement */:
- case 259 /* JsxOpeningFragment */:
- return emitJsxOpeningElementOrFragment(node);
- case 257 /* JsxClosingElement */:
- case 260 /* JsxClosingFragment */:
- return emitJsxClosingElementOrFragment(node);
- case 261 /* JsxAttribute */:
- return emitJsxAttribute(node);
- case 262 /* JsxAttributes */:
- return emitJsxAttributes(node);
- case 263 /* JsxSpreadAttribute */:
- return emitJsxSpreadAttribute(node);
- case 264 /* JsxExpression */:
- return emitJsxExpression(node);
- // Clauses
- case 265 /* CaseClause */:
- return emitCaseClause(node);
- case 266 /* DefaultClause */:
- return emitDefaultClause(node);
- case 267 /* HeritageClause */:
- return emitHeritageClause(node);
- case 268 /* CatchClause */:
- return emitCatchClause(node);
- // Property assignments
- case 269 /* PropertyAssignment */:
- return emitPropertyAssignment(node);
- case 270 /* ShorthandPropertyAssignment */:
- return emitShorthandPropertyAssignment(node);
- case 271 /* SpreadAssignment */:
- return emitSpreadAssignment(node);
- // Enum
- case 272 /* EnumMember */:
- return emitEnumMember(node);
- // JSDoc nodes (ignored)
- // Transformation nodes (ignored)
- }
- // If the node is an expression, try to emit it as an expression with
- // substitution.
- if (ts.isExpression(node)) {
- return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node));
- }
- if (ts.isToken(node)) {
- writeTokenNode(node, writePunctuation);
- return;
- }
- }
- function pipelineEmitExpression(node) {
- var kind = node.kind;
- switch (kind) {
- // Literals
- case 8 /* NumericLiteral */:
- return emitNumericLiteral(node);
- case 9 /* StringLiteral */:
- case 12 /* RegularExpressionLiteral */:
- case 13 /* NoSubstitutionTemplateLiteral */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Reserved words
- case 86 /* FalseKeyword */:
- case 95 /* NullKeyword */:
- case 97 /* SuperKeyword */:
- case 101 /* TrueKeyword */:
- case 99 /* ThisKeyword */:
- case 91 /* ImportKeyword */:
- writeTokenNode(node, writeKeyword);
- return;
- // Expressions
- case 182 /* ArrayLiteralExpression */:
- return emitArrayLiteralExpression(node);
- case 183 /* ObjectLiteralExpression */:
- return emitObjectLiteralExpression(node);
- case 184 /* PropertyAccessExpression */:
- return emitPropertyAccessExpression(node);
- case 185 /* ElementAccessExpression */:
- return emitElementAccessExpression(node);
- case 186 /* CallExpression */:
- return emitCallExpression(node);
- case 187 /* NewExpression */:
- return emitNewExpression(node);
- case 188 /* TaggedTemplateExpression */:
- return emitTaggedTemplateExpression(node);
- case 189 /* TypeAssertionExpression */:
- return emitTypeAssertionExpression(node);
- case 190 /* ParenthesizedExpression */:
- return emitParenthesizedExpression(node);
- case 191 /* FunctionExpression */:
- return emitFunctionExpression(node);
- case 192 /* ArrowFunction */:
- return emitArrowFunction(node);
- case 193 /* DeleteExpression */:
- return emitDeleteExpression(node);
- case 194 /* TypeOfExpression */:
- return emitTypeOfExpression(node);
- case 195 /* VoidExpression */:
- return emitVoidExpression(node);
- case 196 /* AwaitExpression */:
- return emitAwaitExpression(node);
- case 197 /* PrefixUnaryExpression */:
- return emitPrefixUnaryExpression(node);
- case 198 /* PostfixUnaryExpression */:
- return emitPostfixUnaryExpression(node);
- case 199 /* BinaryExpression */:
- return emitBinaryExpression(node);
- case 200 /* ConditionalExpression */:
- return emitConditionalExpression(node);
- case 201 /* TemplateExpression */:
- return emitTemplateExpression(node);
- case 202 /* YieldExpression */:
- return emitYieldExpression(node);
- case 203 /* SpreadElement */:
- return emitSpreadExpression(node);
- case 204 /* ClassExpression */:
- return emitClassExpression(node);
- case 205 /* OmittedExpression */:
- return;
- case 207 /* AsExpression */:
- return emitAsExpression(node);
- case 208 /* NonNullExpression */:
- return emitNonNullExpression(node);
- case 209 /* MetaProperty */:
- return emitMetaProperty(node);
- // JSX
- case 254 /* JsxElement */:
- return emitJsxElement(node);
- case 255 /* JsxSelfClosingElement */:
- return emitJsxSelfClosingElement(node);
- case 258 /* JsxFragment */:
- return emitJsxFragment(node);
- // Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
- return emitPartiallyEmittedExpression(node);
- case 297 /* CommaListExpression */:
- return emitCommaList(node);
- }
+ emit(node.constraint);
}
function trySubstituteNode(hint, node) {
return node && substituteNode && substituteNode(hint, node) || node;
@@ -74151,6 +75166,10 @@ var ts;
writeStringLiteral(text);
}
}
+ // SyntaxKind.UnparsedSource
+ function emitUnparsedSource(unparsed) {
+ write(unparsed.text);
+ }
//
// Identifiers
//
@@ -74201,13 +75220,11 @@ var ts;
function emitParameter(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.dotDotDotToken);
- if (node.name) {
- emitNodeWithWriter(node.name, writeParameter);
- }
- emitIfPresent(node.questionToken);
- if (node.parent && node.parent.kind === 281 /* JSDocFunctionType */ && !node.name) {
- emitIfPresent(node.type);
+ emit(node.dotDotDotToken);
+ emitNodeWithWriter(node.name, writeParameter);
+ emit(node.questionToken);
+ if (node.parent && node.parent.kind === 283 /* JSDocFunctionType */ && !node.name) {
+ emit(node.type);
}
else {
emitTypeAnnotation(node.type);
@@ -74226,7 +75243,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitNodeWithWriter(node.name, writeProperty);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeAnnotation(node.type);
writeSemicolon();
}
@@ -74234,28 +75251,30 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
- emitIfPresent(node.exclamationToken);
+ emit(node.questionToken);
+ emit(node.exclamationToken);
emitTypeAnnotation(node.type);
emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitMethodDeclaration(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitSignatureAndBody(node, emitSignatureHead);
}
function emitConstructor(node) {
@@ -74272,14 +75291,17 @@ var ts;
emitSignatureAndBody(node, emitSignatureHead);
}
function emitCallSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitConstructSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("new");
@@ -74288,6 +75310,7 @@ var ts;
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitIndexSignature(node) {
emitDecorators(node, node.decorators);
@@ -74314,18 +75337,20 @@ var ts;
emitTypeArguments(node, node.typeArguments);
}
function emitFunctionType(node) {
+ pushNameGenerationScope(node);
emitTypeParameters(node, node.typeParameters);
emitParametersForArrow(node, node.parameters);
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitJSDocFunctionType(node) {
write("function");
emitParameters(node, node.parameters);
write(":");
- emitIfPresent(node.type);
+ emit(node.type);
}
function emitJSDocNullableType(node) {
write("?");
@@ -74340,6 +75365,7 @@ var ts;
write("=");
}
function emitConstructorType(node) {
+ pushNameGenerationScope(node);
writeKeyword("new");
writeSpace();
emitTypeParameters(node, node.typeParameters);
@@ -74347,7 +75373,8 @@ var ts;
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitTypeQuery(node) {
writeKeyword("typeof");
@@ -74437,7 +75464,8 @@ var ts;
writeSpace();
}
writePunctuation("[");
- pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */);
+ pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter);
writePunctuation("]");
if (node.questionToken) {
emit(node.questionToken);
@@ -74447,7 +75475,7 @@ var ts;
}
writePunctuation(":");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
writeSemicolon();
if (emitFlags & 1 /* SingleLine */) {
writeSpace();
@@ -74490,7 +75518,7 @@ var ts;
writePunctuation("]");
}
function emitBindingElement(node) {
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
if (node.propertyName) {
emit(node.propertyName);
writePunctuation(":");
@@ -74508,6 +75536,7 @@ var ts;
emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine);
}
function emitObjectLiteralExpression(node) {
+ ts.forEach(node.properties, generateMemberNames);
var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
if (indentedFlag) {
increaseIndent();
@@ -74597,6 +75626,7 @@ var ts;
emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
+ generateNameIfNeeded(node.name);
emitFunctionDeclarationOrExpression(node);
}
function emitArrowFunction(node) {
@@ -74696,7 +75726,7 @@ var ts;
}
function emitYieldExpression(node) {
emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
@@ -74704,6 +75734,7 @@ var ts;
emitExpression(node.expression);
}
function emitClassExpression(node) {
+ generateNameIfNeeded(node.name);
emitClassDeclarationOrExpression(node);
}
function emitExpressionWithTypeArguments(node) {
@@ -74757,7 +75788,9 @@ var ts;
}
function emitExpressionStatement(node) {
emitExpression(node.expression);
- writeSemicolon();
+ if (!ts.isJsonSourceFile(currentSourceFile)) {
+ writeSemicolon();
+ }
}
function emitIfStatement(node) {
var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
@@ -74953,7 +75986,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("function");
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
writeSpace();
emitIdentifierName(node.name);
emitSignatureAndBody(node, emitSignatureHead);
@@ -74970,6 +76003,8 @@ var ts;
increaseIndent();
}
pushNameGenerationScope(node);
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
emitSignatureHead(node);
if (onEmitNode) {
onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
@@ -75065,6 +76100,7 @@ var ts;
emitClassDeclarationOrExpression(node);
}
function emitClassDeclarationOrExpression(node) {
+ ts.forEach(node.members, generateMemberNames);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("class");
@@ -75142,6 +76178,7 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
popNameGenerationScope(node);
}
@@ -75183,12 +76220,12 @@ var ts;
writeSemicolon();
}
function emitImportClause(node) {
- emitIfPresent(node.name);
+ emit(node.name);
if (node.name && node.namedBindings) {
emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
writeSpace();
}
- emitIfPresent(node.namedBindings);
+ emit(node.namedBindings);
}
function emitNamespaceImport(node) {
var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
@@ -75330,7 +76367,7 @@ var ts;
function emitJsxExpression(node) {
if (node.expression) {
writePunctuation("{");
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
emitExpression(node.expression);
writePunctuation("}");
}
@@ -75486,8 +76523,8 @@ var ts;
write("/// ");
writeLine();
}
- for (var _d = 0, types_18 = types; _d < types_18.length; _d++) {
- var directive = types_18[_d];
+ for (var _d = 0, types_17 = types; _d < types_17.length; _d++) {
+ var directive = types_17[_d];
write("/// ");
writeLine();
}
@@ -75495,6 +76532,7 @@ var ts;
function emitSourceFileWorker(node) {
var statements = node.statements;
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitHelpers(node);
var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
emitTripleSlashDirectivesIfNeeded(node);
@@ -75571,6 +76609,8 @@ var ts;
// Helpers
//
function emitNodeWithWriter(node, writer) {
+ if (!node)
+ return;
var savedWrite = write;
write = writer;
emit(node);
@@ -76060,7 +77100,7 @@ var ts;
if (ts.isGeneratedIdentifier(node)) {
return generateName(node);
}
- else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
+ else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
return ts.idText(node);
}
else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) {
@@ -76112,6 +77152,113 @@ var ts;
}
reservedNames.set(name, true);
}
+ function generateNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 212 /* Block */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 227 /* LabeledStatement */:
+ case 225 /* WithStatement */:
+ case 217 /* DoStatement */:
+ case 218 /* WhileStatement */:
+ generateNames(node.statement);
+ break;
+ case 216 /* IfStatement */:
+ generateNames(node.thenStatement);
+ generateNames(node.elseStatement);
+ break;
+ case 219 /* ForStatement */:
+ case 221 /* ForOfStatement */:
+ case 220 /* ForInStatement */:
+ generateNames(node.initializer);
+ generateNames(node.statement);
+ break;
+ case 226 /* SwitchStatement */:
+ generateNames(node.caseBlock);
+ break;
+ case 240 /* CaseBlock */:
+ ts.forEach(node.clauses, generateNames);
+ break;
+ case 265 /* CaseClause */:
+ case 266 /* DefaultClause */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 229 /* TryStatement */:
+ generateNames(node.tryBlock);
+ generateNames(node.catchClause);
+ generateNames(node.finallyBlock);
+ break;
+ case 268 /* CatchClause */:
+ generateNames(node.variableDeclaration);
+ generateNames(node.block);
+ break;
+ case 213 /* VariableStatement */:
+ generateNames(node.declarationList);
+ break;
+ case 232 /* VariableDeclarationList */:
+ ts.forEach(node.declarations, generateNames);
+ break;
+ case 231 /* VariableDeclaration */:
+ case 148 /* Parameter */:
+ case 181 /* BindingElement */:
+ case 234 /* ClassDeclaration */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 233 /* FunctionDeclaration */:
+ generateNameIfNeeded(node.name);
+ if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
+ }
+ break;
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 243 /* ImportDeclaration */:
+ generateNames(node.importClause);
+ break;
+ case 244 /* ImportClause */:
+ generateNameIfNeeded(node.name);
+ generateNames(node.namedBindings);
+ break;
+ case 245 /* NamespaceImport */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 246 /* NamedImports */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 247 /* ImportSpecifier */:
+ generateNameIfNeeded(node.propertyName || node.name);
+ break;
+ }
+ }
+ function generateMemberNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 269 /* PropertyAssignment */:
+ case 270 /* ShorthandPropertyAssignment */:
+ case 151 /* PropertyDeclaration */:
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ generateNameIfNeeded(node.name);
+ break;
+ }
+ }
+ function generateNameIfNeeded(name) {
+ if (name) {
+ if (ts.isGeneratedIdentifier(name)) {
+ generateName(name);
+ }
+ else if (ts.isBindingPattern(name)) {
+ generateNames(name);
+ }
+ }
+ }
/**
* Generate the text for a generated identifier.
*/
@@ -76119,17 +77266,7 @@ var ts;
if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
// Node names generate unique names based on their original node
// and are cached based on that node's id.
- if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) {
- var savedTempFlags = tempFlags;
- popNameGenerationScope(/*node*/ undefined);
- var result = generateNameCached(getNodeForGeneratedName(name));
- pushNameGenerationScope(/*node*/ undefined);
- tempFlags = savedTempFlags;
- return result;
- }
- else {
- return generateNameCached(getNodeForGeneratedName(name));
- }
+ return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
}
else {
// Auto, Loop, and Unique names are cached based on their unique
@@ -76138,9 +77275,9 @@ var ts;
return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
}
}
- function generateNameCached(node) {
+ function generateNameCached(node, flags) {
var nodeId = ts.getNodeId(node);
- return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node));
+ return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
}
/**
* Returns a value indicating whether a name is unique globally, within the current file,
@@ -76155,7 +77292,7 @@ var ts;
* Returns a value indicating whether a name is unique globally or within the current file.
*/
function isFileLevelUniqueName(name) {
- return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName);
+ return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
}
/**
* Returns a value indicating whether a name is unique within a container.
@@ -76212,11 +77349,16 @@ var ts;
* makeUniqueName are guaranteed to never conflict.
* If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
*/
- function makeUniqueName(baseName, checkFn, optimistic) {
+ function makeUniqueName(baseName, checkFn, optimistic, scoped) {
if (checkFn === void 0) { checkFn = isUniqueName; }
if (optimistic) {
if (checkFn(baseName)) {
- generatedNames.set(baseName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(baseName);
+ }
+ else {
+ generatedNames.set(baseName, true);
+ }
return baseName;
}
}
@@ -76228,7 +77370,12 @@ var ts;
while (true) {
var generatedName = baseName + i;
if (checkFn(generatedName)) {
- generatedNames.set(generatedName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(generatedName);
+ }
+ else {
+ generatedNames.set(generatedName, true);
+ }
return generatedName;
}
i++;
@@ -76275,10 +77422,10 @@ var ts;
/**
* Generates a unique name from a node.
*/
- function generateNameForNode(node) {
+ function generateNameForNode(node, flags) {
switch (node.kind) {
case 71 /* Identifier */:
- return makeUniqueName(getTextOfNode(node));
+ return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
case 238 /* ModuleDeclaration */:
case 237 /* EnumDeclaration */:
return generateNameForModuleOrEnum(node);
@@ -76305,11 +77452,11 @@ var ts;
function makeName(name) {
switch (name.autoGenerateFlags & 7 /* KindMask */) {
case 1 /* Auto */:
- return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 2 /* Loop */:
- return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 3 /* Unique */:
- return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32 /* Optimistic */));
+ return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
}
ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
}
@@ -76325,7 +77472,7 @@ var ts;
// if "node" is a different generated name (having a different
// "autoGenerateId"), use it and stop traversing.
if (ts.isIdentifier(node)
- && node.autoGenerateFlags === 4 /* Node */
+ && !!(node.autoGenerateFlags & 4 /* Node */)
&& node.autoGenerateId !== autoGenerateId) {
break;
}
@@ -76384,7 +77531,7 @@ var ts;
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function getCachedFileSystemEntries(rootDirPath) {
- return cachedReadDirectoryResult.get(rootDirPath);
+ return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
}
function getCachedFileSystemEntriesForBaseDir(path) {
return getCachedFileSystemEntries(ts.getDirectoryPath(path));
@@ -76397,7 +77544,7 @@ var ts;
files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
directories: host.getDirectories(rootDir) || []
};
- cachedReadDirectoryResult.set(rootDirPath, resultFromHost);
+ cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
return resultFromHost;
}
/**
@@ -76406,6 +77553,7 @@ var ts;
* The host request is done under try catch block to avoid caching incorrect result
*/
function tryReadDirectory(rootDir, rootDirPath) {
+ rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
var cachedResult = getCachedFileSystemEntries(rootDirPath);
if (cachedResult) {
return cachedResult;
@@ -76415,7 +77563,7 @@ var ts;
}
catch (_e) {
// If there is exception to read directories, dont cache the result and direct the calls to host
- ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath));
+ ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
return undefined;
}
}
@@ -76451,7 +77599,7 @@ var ts;
}
function directoryExists(dirPath) {
var path = toPath(dirPath);
- return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath);
+ return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
}
function createDirectory(dirPath) {
var path = toPath(dirPath);
@@ -76725,7 +77873,7 @@ var ts;
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
- return ts.getNormalizedPathFromPathComponents(commonPathComponents);
+ return ts.getPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
function createCompilerHost(options, setParentNodes) {
@@ -76832,7 +77980,8 @@ var ts;
directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); },
getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return ts.sys.getDirectories(path); },
- realpath: realpath
+ realpath: realpath,
+ readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }
};
}
ts.createCompilerHost = createCompilerHost;
@@ -76900,52 +78049,52 @@ var ts;
var output = "";
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
- var context = "";
+ var context_2 = "";
if (diagnostic.file) {
- var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file;
- var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
- var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
- var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
- var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
+ var start = diagnostic.start, length_4 = diagnostic.length, file_9 = diagnostic.file;
+ var _a = ts.getLineAndCharacterOfPosition(file_9, start), firstLine = _a.line, firstLineChar = _a.character;
+ var _b = ts.getLineAndCharacterOfPosition(file_9, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
+ var lastLineInFile = ts.getLineAndCharacterOfPosition(file_9, file_9.text.length).line;
+ var relativeFileName = host ? ts.convertToRelativePath(file_9.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_9.fileName;
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
for (var i = firstLine; i <= lastLine; i++) {
- context += host.getNewLine();
+ context_2 += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
- context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
}
- var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
- var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
- var lineContent = file.text.slice(lineStart, lineEnd);
+ var lineStart = ts.getPositionOfLineAndCharacter(file_9, i, 0);
+ var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_9, i + 1, 0) : file_9.text.length;
+ var lineContent = file_9.text.slice(lineStart, lineEnd);
lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
// Output the gutter and the actual contents of the line.
- context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += lineContent + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += lineContent + host.getNewLine();
// Output the gutter and the error span for the line using tildes.
- context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += ForegroundColorEscapeSequences.Red;
+ context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += ForegroundColorEscapeSequences.Red;
if (i === firstLine) {
// If we're on the last line, then limit it to the last character of the last line.
// Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
var lastCharForLine = i === lastLine ? lastLineChar : undefined;
- context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
- context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
+ context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
+ context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
}
else if (i === lastLine) {
- context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
+ context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~");
}
else {
// Squiggle the entire line.
- context += lineContent.replace(/./g, "~");
+ context_2 += lineContent.replace(/./g, "~");
}
- context += resetEscapeSequence;
+ context_2 += resetEscapeSequence;
}
output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan);
output += ":";
@@ -76959,7 +78108,7 @@ var ts;
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
output += host.getNewLine();
- output += context;
+ output += context_2;
}
output += host.getNewLine();
}
@@ -77069,21 +78218,19 @@ var ts;
oldOptions.baseUrl !== newOptions.baseUrl ||
!ts.equalOwnProperties(oldOptions.paths, newOptions.paths));
}
- /**
- * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions'
- * that represent a compilation unit.
- *
- * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and
- * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in.
- *
- * @param rootNames - A set of root files.
- * @param options - The compiler options which should be used.
- * @param host - The host interacts with the underlying file system.
- * @param oldProgram - Reuses an old program structure.
- * @param configFileParsingDiagnostics - error during config file parsing
- * @returns A 'Program' object.
- */
- function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ return {
+ rootNames: rootNames,
+ options: options,
+ host: host,
+ oldProgram: oldProgram,
+ configFileParsingDiagnostics: configFileParsingDiagnostics
+ };
+ }
+ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
+ var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions;
+ var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
+ var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram;
var program;
var files = [];
var commonSourceDirectory;
@@ -77111,6 +78258,7 @@ var ts;
var sourceFilesFoundSearchingNodeModules = ts.createMap();
ts.performance.mark("beforeProgram");
host = host || createCompilerHost(options);
+ var configParsingHost = parseConfigHostFromCompilerHost(host);
var skipDefaultLib = options.noLib;
var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
@@ -77120,6 +78268,7 @@ var ts;
// Map storing if there is emit blocking diagnostics for given input
var hasEmitBlockingDiagnostics = ts.createMap();
var _compilerOptionsObjectLiteralSyntax;
+ var _referencesArrayLiteralSyntax;
var moduleResolutionCache;
var resolveModuleNamesWorker;
var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
@@ -77159,6 +78308,23 @@ var ts;
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
+ // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
+ var resolvedProjectReferences = projectReferences ? [] : undefined;
+ var projectReferenceRedirects = ts.createMap();
+ if (projectReferences) {
+ for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) {
+ var ref = projectReferences_1[_i];
+ var parsedRef = parseProjectReferenceConfigFile(ref);
+ resolvedProjectReferences.push(parsedRef);
+ if (parsedRef) {
+ if (parsedRef.commandLine.options.outFile) {
+ var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts");
+ processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects);
+ }
+ }
+ }
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -77198,8 +78364,8 @@ var ts;
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) {
- var oldSourceFile = oldSourceFiles_1[_i];
+ for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
+ var oldSourceFile = oldSourceFiles_1[_a];
if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) {
host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions());
}
@@ -77240,6 +78406,7 @@ var ts;
isEmittedFile: isEmittedFile,
getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
+ getProjectReferences: getProjectReferences
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -77255,9 +78422,14 @@ var ts;
if (commonSourceDirectory === undefined) {
var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
- // If a rootDir is specified and is valid use it as the commonSourceDirectory
+ // If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
+ else if (options.composite) {
+ // Project compilations never infer their root from the input source paths
+ commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
+ checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
+ }
else {
commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
}
@@ -77295,16 +78467,16 @@ var ts;
// We only set `file.resolvedModules` via work from the current function,
// so it is defined iff we already called the current function on `file`.
// That call happened no later than the creation of the `file` object,
- // which per above occured during the current program creation.
+ // which per above occurred during the current program creation.
// Since we assume the filesystem does not change during program creation,
// it is safe to reuse resolutions from the earlier call.
- var result_3 = [];
+ var result_4 = [];
for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
var moduleName = moduleNames_1[_i];
var resolvedModule = file.resolvedModules.get(moduleName);
- result_3.push(resolvedModule);
+ result_4.push(resolvedModule);
}
- return result_3;
+ return result_4;
}
// At this point, we know at least one of the following hold:
// - file has local declarations for ambient modules
@@ -77435,6 +78607,34 @@ var ts;
if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
return oldProgram.structureIsReused = 0 /* Not */;
}
+ // Check if any referenced project tsconfig files are different
+ var oldRefs = oldProgram.getProjectReferences();
+ if (projectReferences) {
+ if (!oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ for (var i = 0; i < projectReferences.length; i++) {
+ var oldRef = oldRefs[i];
+ if (oldRef) {
+ var newRef = parseProjectReferenceConfigFile(projectReferences[i]);
+ if (!newRef || newRef.sourceFile !== oldRef.sourceFile) {
+ // Resolved project reference has gone missing or changed
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ else {
+ // A previously-unresolved reference may be resolved now
+ if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ }
+ }
+ else {
+ if (oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
// check if program source files has changed in the way that can affect structure of the program
var newSourceFiles = [];
var filePaths = [];
@@ -77602,6 +78802,7 @@ var ts;
}
function getEmitHost(writeFileCallback) {
return {
+ getPrependNodes: getPrependNodes,
getCanonicalFileName: getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
@@ -77615,6 +78816,32 @@ var ts;
isEmitBlocked: isEmitBlocked,
};
}
+ function getProjectReferences() {
+ if (!resolvedProjectReferences)
+ return;
+ return resolvedProjectReferences;
+ }
+ function getPrependNodes() {
+ if (!projectReferences) {
+ return ts.emptyArray;
+ }
+ var nodes = [];
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!resolvedRefOpts.options.outFile)
+ continue;
+ var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts");
+ var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n";
+ var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n";
+ var node = ts.createInputFiles(js, dts);
+ nodes.push(node);
+ }
+ }
+ return nodes;
+ }
function isSourceFileFromExternalLibrary(file) {
return sourceFilesFoundSearchingNodeModules.get(file.path);
}
@@ -77685,7 +78912,7 @@ var ts;
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -77769,9 +78996,9 @@ var ts;
var typeChecker = getDiagnosticsProducingTypeChecker();
ts.Debug.assert(!!sourceFile.bindDiagnostics);
var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
- // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins)
+ // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
- sourceFile.scriptKind === 5 /* External */ || isCheckJs;
+ sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */;
var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
@@ -78147,7 +79374,13 @@ var ts;
var sourceFile = getSourceFile(fileName);
if (fail) {
if (!sourceFile) {
- fail(ts.Diagnostics.File_0_not_found, fileName);
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
+ }
+ else {
+ fail(ts.Diagnostics.File_0_not_found, fileName);
+ }
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
@@ -78208,31 +79441,45 @@ var ts;
// Get source file from normalized fileName
function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) {
if (filesByName.has(path)) {
- var file_1 = filesByName.get(path);
+ var file_10 = filesByName.get(path);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
- if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
- reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
+ if (file_10 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_10.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
+ reportFileNamesDifferOnlyInCasingError(fileName, file_10.fileName, refFile, refPos, refEnd);
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
- if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) {
- sourceFilesFoundSearchingNodeModules.set(file_1.path, false);
+ if (file_10 && sourceFilesFoundSearchingNodeModules.get(file_10.path) && currentNodeModulesDepth === 0) {
+ sourceFilesFoundSearchingNodeModules.set(file_10.path, false);
if (!options.noResolve) {
- processReferencedFiles(file_1, isDefaultLib);
- processTypeReferenceDirectives(file_1);
+ processReferencedFiles(file_10, isDefaultLib);
+ processTypeReferenceDirectives(file_10);
}
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_10.path, false);
+ processImportedModules(file_10);
}
// See if we need to reprocess the imports due to prior skipped imports
- else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
+ else if (file_10 && modulesWithElidedImports.get(file_10.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_10.path, false);
+ processImportedModules(file_10);
}
}
- return file_1;
+ return file_10;
+ }
+ var redirectedPath;
+ if (refFile) {
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
+ fileName = redirect;
+ // Once we start redirecting to a file, we can potentially come back to it
+ // via a back-reference from another file in the .d.ts folder. If that happens we'll
+ // end up trying to add it to the program *again* because we were tracking it via its
+ // original (un-redirected) name. So we have to map both the original path and the redirected path
+ // to the source file we're about to find/create
+ redirectedPath = toPath(redirect);
+ }
}
// We haven't looked for this file, do so now and cache result
var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
@@ -78263,6 +79510,9 @@ var ts;
}
}
filesByName.set(path, file);
+ if (redirectedPath) {
+ filesByName.set(redirectedPath, file);
+ }
if (file) {
sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
file.path = path;
@@ -78293,6 +79543,22 @@ var ts;
}
return file;
}
+ function getProjectReferenceRedirect(fileName) {
+ var path = toPath(fileName);
+ // If this file is produced by a referenced project, we need to rewrite it to
+ // look in the output folder of the referenced project rather than the input
+ var normalized = ts.getNormalizedAbsolutePath(fileName, path);
+ var result;
+ projectReferenceRedirects.forEach(function (v, k) {
+ if (result !== undefined) {
+ return undefined;
+ }
+ if (normalized.indexOf(k) === 0) {
+ result = ts.changeExtension(fileName.replace(k, v), ".d.ts");
+ }
+ });
+ return result;
+ }
function processReferencedFiles(file, isDefaultLib) {
ts.forEach(file.referencedFiles, function (ref) {
var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
@@ -78302,6 +79568,9 @@ var ts;
function processTypeReferenceDirectives(file) {
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
+ if (!typeDirectives) {
+ return;
+ }
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName);
for (var i = 0; i < typeDirectives.length; i++) {
var ref = file.typeReferenceDirectives[i];
@@ -78381,7 +79650,7 @@ var ts;
continue;
}
var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
- var isJsFile = !ts.extensionIsTypeScript(resolution.extension);
+ var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension);
var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
var resolvedFileName = resolution.resolvedFileName;
if (isFromNodeModulesSearch) {
@@ -78423,9 +79692,9 @@ var ts;
function computeCommonSourceDirectory(sourceFiles) {
var fileNames = [];
for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
- var file = sourceFiles_2[_i];
- if (!file.isDeclarationFile) {
- fileNames.push(file.fileName);
+ var file_11 = sourceFiles_2[_i];
+ if (!file_11.isDeclarationFile) {
+ fileNames.push(file_11.fileName);
}
}
return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
@@ -78447,6 +79716,27 @@ var ts;
}
return allFilesBelongToPath;
}
+ function parseProjectReferenceConfigFile(ref) {
+ // The actual filename (i.e. add "/tsconfig.json" if necessary)
+ var refPath = resolveProjectReferencePath(host, ref);
+ // An absolute path pointing to the containing directory of the config file
+ var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
+ var sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
+ if (sourceFile === undefined) {
+ return undefined;
+ }
+ var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
+ return { commandLine: commandLine, sourceFile: sourceFile };
+ }
+ function addProjectReferenceRedirects(referencedProject, target) {
+ var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath));
+ target.set(rootDir, getDeclarationOutputDirectory(referencedProject));
+ }
+ function getDeclarationOutputDirectory(proj) {
+ return proj.options.declarationDir ||
+ proj.options.outDir ||
+ ts.getDirectoryPath(proj.options.configFilePath);
+ }
function verifyCompilerOptions() {
if (options.strictPropertyInitialization && !options.strictNullChecks) {
createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
@@ -78476,6 +79766,48 @@ var ts;
if (options.paths && options.baseUrl === undefined) {
createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
}
+ if (options.composite) {
+ if (options.declaration === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
+ }
+ }
+ if (projectReferences) {
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options;
+ if (resolvedRefOpts === undefined) {
+ createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path);
+ continue;
+ }
+ if (!resolvedRefOpts.composite) {
+ createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
+ }
+ if (ref.prepend) {
+ if (resolvedRefOpts.outFile) {
+ if (!host.fileExists(resolvedRefOpts.outFile)) {
+ createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path);
+ }
+ }
+ else {
+ createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
+ }
+ }
+ }
+ }
+ // List of collected files is complete; validate exhautiveness if this is a project with a file list
+ if (options.composite && rootNames.length < files.length) {
+ var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
+ var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); });
+ var _loop_10 = function (file_12) {
+ if (normalizedRootNames.every(function (r) { return r !== file_12; })) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_12));
+ }
+ };
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var file_12 = sourceFiles_4[_i];
+ _loop_10(file_12);
+ }
+ }
if (options.paths) {
for (var key in options.paths) {
if (!ts.hasProperty(options.paths, key)) {
@@ -78567,6 +79899,11 @@ var ts;
programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
}
}
+ if (options.resolveJsonModule) {
+ if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
+ }
+ }
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
@@ -78679,12 +80016,15 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
}
}
- function getOptionPathsSyntax() {
+ function getOptionsSyntaxByName(name) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
if (compilerOptionsObjectLiteralSyntax) {
- return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths");
+ return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
}
- return ts.emptyArray;
+ return undefined;
+ }
+ function getOptionPathsSyntax() {
+ return getOptionsSyntaxByName("paths") || ts.emptyArray;
}
function createDiagnosticForOptionName(message, option1, option2, option3) {
createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
@@ -78692,6 +80032,15 @@ var ts;
function createOptionValueDiagnostic(option1, message, arg0) {
createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
}
+ function createDiagnosticForReference(index, message, arg0, arg1) {
+ var referencesSyntax = getProjectReferencesSyntax();
+ if (referencesSyntax) {
+ if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) {
+ return;
+ }
+ }
+ programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
+ }
function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
@@ -78700,11 +80049,28 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
}
}
+ function getProjectReferencesSyntax() {
+ if (_referencesArrayLiteralSyntax === undefined) {
+ _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword
+ if (options.configFile) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (ts.isArrayLiteralExpression(prop.initializer)) {
+ _referencesArrayLiteralSyntax = prop.initializer;
+ break;
+ }
+ }
+ }
+ }
+ return _referencesArrayLiteralSyntax;
+ }
function getCompilerOptionsObjectLiteralSyntax() {
if (_compilerOptionsObjectLiteralSyntax === undefined) {
_compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword
- if (options.configFile && options.configFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ if (jsonObjectLiteral) {
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
var prop = _a[_i];
if (ts.isObjectLiteralExpression(prop.initializer)) {
_compilerOptionsObjectLiteralSyntax = prop.initializer;
@@ -78723,6 +80089,13 @@ var ts;
}
return !!props.length;
}
+ function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) {
+ if (arrayLiteral.elements.length <= index) {
+ // Out-of-bounds
+ return false;
+ }
+ programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2));
+ }
function blockEmittingOfFile(emitFileName, diag) {
hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
programDiagnostics.add(diag);
@@ -78759,6 +80132,27 @@ var ts;
}
ts.createProgram = createProgram;
/* @internal */
+ function parseConfigHostFromCompilerHost(host) {
+ return {
+ fileExists: function (f) { return host.fileExists(f); },
+ readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; },
+ readFile: function (f) { return host.readFile(f); },
+ useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ onUnRecoverableConfigFileDiagnostic: function () { return undefined; }
+ };
+ }
+ ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost;
+ /**
+ * Returns the target config filename of a project reference
+ */
+ function resolveProjectReferencePath(host, ref) {
+ if (!host.fileExists(ref.path)) {
+ return ts.combinePaths(ref.path, "tsconfig.json");
+ }
+ return ref.path;
+ }
+ /* @internal */
/**
* Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
* The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
@@ -78769,6 +80163,7 @@ var ts;
switch (extension) {
case ".ts" /* Ts */:
case ".d.ts" /* Dts */:
+ case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check
// These are always allowed.
return undefined;
case ".tsx" /* Tsx */:
@@ -78969,6 +80364,7 @@ var ts;
* Get all the dependencies of the sourceFile
*/
function getAllDependencies(state, programOfThisState, sourceFile) {
+ var _a;
var compilerOptions = programOfThisState.getCompilerOptions();
// With --out or --outFile all outputs go into single file, all files depend on each other
if (compilerOptions.outFile || compilerOptions.out) {
@@ -78988,7 +80384,7 @@ var ts;
var references = state.referencedMap.get(path);
if (references) {
var iterator = references.keys();
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
queue.push(value);
}
}
@@ -78998,7 +80394,6 @@ var ts;
var file = programOfThisState.getSourceFileByPath(path);
return file ? file.fileName : path;
}));
- var _b;
}
BuilderState.getAllDependencies = getAllDependencies;
/**
@@ -79443,8 +80838,8 @@ var ts;
}
var diagnostics;
for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_1 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
+ var sourceFile_2 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
@@ -79522,6 +80917,7 @@ var ts;
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
+ getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsOfFile: removeResolutionsOfFile,
invalidateResolutionOfFile: invalidateResolutionOfFile,
@@ -79694,6 +81090,10 @@ var ts;
function resolveModuleNames(moduleNames, containingFile, reusedNames) {
return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
}
+ function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
+ var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
+ return cache && cache.get(moduleName);
+ }
function isNodeModulesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules");
}
@@ -79741,17 +81141,19 @@ var ts;
return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath));
}
// Use some ancestor of the root directory
+ var subDirectory;
if (rootPath !== undefined) {
while (!isInDirectoryPath(dirPath, rootPath)) {
var parentPath = ts.getDirectoryPath(dirPath);
if (parentPath === dirPath) {
break;
}
+ subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length);
dirPath = parentPath;
dir = ts.getDirectoryPath(dir);
}
}
- return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath);
+ return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath);
}
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
@@ -79771,7 +81173,7 @@ var ts;
for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
// If the failed lookup location path is not one of the supported extensions,
// store it in the custom path
@@ -79783,7 +81185,7 @@ var ts;
setAtRoot = true;
}
else {
- setDirectoryWatcher(dir, dirPath);
+ setDirectoryWatcher(dir, dirPath, subDirectory);
}
}
}
@@ -79791,13 +81193,19 @@ var ts;
setDirectoryWatcher(rootDir, rootPath);
}
}
- function setDirectoryWatcher(dir, dirPath) {
+ function setDirectoryWatcher(dir, dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
if (dirWatcher) {
dirWatcher.refCount++;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 };
+ directoryWatchesOfFailedLookups.set(dirPath, dirWatcher);
+ }
+ if (subDirectory) {
+ var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap());
+ var existing = subDirectoryMap.get(subDirectory) || 0;
+ subDirectoryMap.set(subDirectory, existing + 1);
}
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
@@ -79813,7 +81221,7 @@ var ts;
for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
if (refCount) {
@@ -79829,7 +81237,7 @@ var ts;
removeAtRoot = true;
}
else {
- removeDirectoryWatcher(dirPath);
+ removeDirectoryWatcher(dirPath, subDirectory);
}
}
}
@@ -79837,22 +81245,40 @@ var ts;
removeDirectoryWatcher(rootPath);
}
}
- function removeDirectoryWatcher(dirPath) {
+ function removeDirectoryWatcher(dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (subDirectory) {
+ var existing = dirWatcher.subDirectoryMap.get(subDirectory);
+ if (existing === 1) {
+ dirWatcher.subDirectoryMap.delete(subDirectory);
+ }
+ else {
+ dirWatcher.subDirectoryMap.set(subDirectory, existing - 1);
+ }
+ }
// Do not close the watcher yet since it might be needed by other failed lookup locations.
dirWatcher.refCount--;
}
+ function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (!dirWatcher || !dirWatcher.subDirectoryMap)
+ return false;
+ return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) {
+ var fullSubDirectory = dirPath + "/" + subDirectory;
+ return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath);
+ });
+ }
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// If the files are added to project root or node_modules directory, always run through the invalidation process
// Otherwise run through invalidation only if adding to the immediate directory
if (!allFilesHaveInvalidatedResolution &&
- dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) {
+ (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) {
if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
resolutionHost.onInvalidatedResolution();
}
@@ -79976,7 +81402,7 @@ var ts;
return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// For now just recompile
@@ -80112,34 +81538,11 @@ var ts;
function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) {
var host = system;
host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); };
- var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
+ var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
host.onUnRecoverableConfigFileDiagnostic = undefined;
return result;
}
ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
- /**
- * Reads the config file, reports errors if any and exits if the config file cannot be found
- */
- function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
- var configFileText;
- try {
- configFileText = host.readFile(configFileName);
- }
- catch (e) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- if (!configFileText) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- var result = ts.parseJsonText(configFileName, configFileText);
- var cwd = host.getCurrentDirectory();
- return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
- }
- ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
*/
@@ -80221,12 +81624,12 @@ var ts;
watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; },
watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; },
setTimeout: system.setTimeout ? (function (callback, ms) {
+ var _a;
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args));
- var _a;
}) : ts.noop,
clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop,
trace: function (s) { return system.write(s); },
@@ -80986,6 +82389,13 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
+ {
+ name: "composite",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_project_compilation,
+ },
{
name: "removeComments",
type: "boolean",
@@ -81246,6 +82656,12 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "resolveJsonModule",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Include_modules_imported_with_json_extension
+ },
{
name: "listFiles",
type: "boolean",
@@ -81539,11 +82955,13 @@ var ts;
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
+ var projectReferences = undefined;
var errors = [];
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
errors: errors
};
function parseStrings(args) {
@@ -81656,6 +83074,29 @@ var ts;
}
return optionNameMap.get(optionName);
}
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
+ var configFileText;
+ try {
+ configFileText = host.readFile(configFileName);
+ }
+ catch (e) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ if (!configFileText) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ var result = ts.parseJsonText(configFileName, configFileText);
+ var cwd = host.getCurrentDirectory();
+ return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
+ }
+ ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -81703,55 +83144,67 @@ var ts;
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
if (_tsconfigRootOptions === undefined) {
- _tsconfigRootOptions = commandLineOptionsToMap([
- {
- name: "compilerOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
- },
- {
- name: "typingOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "typeAcquisition",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "extends",
- type: "string"
- },
- {
- name: "files",
- type: "list",
- element: {
+ _tsconfigRootOptions = {
+ name: undefined,
+ type: "object",
+ elementOptions: commandLineOptionsToMap([
+ {
+ name: "compilerOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
+ },
+ {
+ name: "typingOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "typeAcquisition",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "extends",
+ type: "string"
+ },
+ {
+ name: "references",
+ type: "list",
+ element: {
+ name: "references",
+ type: "object"
+ }
+ },
+ {
name: "files",
- type: "string"
- }
- },
- {
- name: "include",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "files",
+ type: "string"
+ }
+ },
+ {
name: "include",
- type: "string"
- }
- },
- {
- name: "exclude",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
+ }
+ },
+ {
name: "exclude",
- type: "string"
- }
- },
- ts.compileOnSaveCommandLineOption
- ]);
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
+ }
+ },
+ ts.compileOnSaveCommandLineOption
+ ])
+ };
}
return _tsconfigRootOptions;
}
@@ -81759,20 +83212,25 @@ var ts;
* Convert the json syntax tree into the json value
*/
function convertToObject(sourceFile, errors) {
- return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
}
ts.convertToObject = convertToObject;
/**
- * Convert the json syntax tree into the json value
+ * Convert the json syntax tree into the json value and report errors
+ * This returns the json value (apart from checking errors) only if returnValue provided is true.
+ * Otherwise it just checks the errors and returns undefined
*/
- function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) {
- if (!sourceFile.jsonObject) {
- return {};
+ /*@internal*/
+ function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
+ if (!sourceFile.statements.length) {
+ return returnValue ? {} : undefined;
+ }
+ return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
+ function isRootOptionMap(knownOptions) {
+ return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
}
- return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions,
- /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined);
function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
- var result = {};
+ var result = returnValue ? {} : undefined;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var element = _a[_i];
if (element.kind !== 269 /* PropertyAssignment */) {
@@ -81792,11 +83250,13 @@ var ts;
}
var value = convertPropertyValueToJson(element.initializer, option);
if (typeof keyText !== "undefined") {
- result[keyText] = value;
+ if (returnValue) {
+ result[keyText] = value;
+ }
// Notify key value set, if user asked for it
if (jsonConversionNotifier &&
// Current callbacks are only on known parent option or if we are setting values in the root
- (parentOption || knownOptions === knownRootOptions)) {
+ (parentOption || isRootOptionMap(knownOptions))) {
var isValidOptionValue = isCompilerOptionsValue(option, value);
if (parentOption) {
if (isValidOptionValue) {
@@ -81804,7 +83264,7 @@ var ts;
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
}
}
- else if (knownOptions === knownRootOptions) {
+ else if (isRootOptionMap(knownOptions)) {
if (isValidOptionValue) {
// Notify about the valid root key value being set
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
@@ -81820,7 +83280,7 @@ var ts;
return result;
}
function convertArrayLiteralExpressionToJson(elements, elementOption) {
- return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); });
}
function convertPropertyValueToJson(valueExpression, option) {
switch (valueExpression.kind) {
@@ -81895,6 +83355,7 @@ var ts;
return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
}
}
+ ts.convertToObjectWorker = convertToObjectWorker;
function getCompilerOptionValueTypeString(option) {
return option.type === "list" ?
"Array" :
@@ -81944,7 +83405,7 @@ var ts;
function serializeCompilerOptions(options) {
var result = ts.createMap();
var optionsNameMap = getOptionNameMap().optionNameMap;
- var _loop_9 = function (name) {
+ var _loop_11 = function (name) {
if (ts.hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
@@ -81973,7 +83434,7 @@ var ts;
}
};
for (var name in options) {
- _loop_9(name);
+ _loop_11(name);
}
return result;
}
@@ -82123,12 +83584,13 @@ var ts;
var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
var raw = parsedConfig.raw;
var options = ts.extend(existingOptions, parsedConfig.options || {});
- options.configFilePath = configFileName;
+ options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
setConfigFileInOptions(options, sourceFile);
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
+ var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences;
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
raw: raw,
errors: errors,
@@ -82167,19 +83629,43 @@ var ts;
createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
}
}
- else {
- var outDir = raw.compilerOptions && raw.compilerOptions.outDir;
- if (outDir) {
- excludeSpecs = [outDir];
+ else if (raw.compilerOptions) {
+ var outDir = raw.compilerOptions.outDir;
+ var declarationDir = raw.compilerOptions.declarationDir;
+ if (outDir || declarationDir) {
+ excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
}
}
if (filesSpecs === undefined && includeSpecs === undefined) {
includeSpecs = ["**/*"];
}
var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) {
+ if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) {
errors.push(getErrorForNoInputFiles(result.spec, configFileName));
}
+ if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
+ if (ts.isArray(raw.references)) {
+ var references = [];
+ for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
+ var ref = _a[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ references.push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
+ }
+ }
+ result.projectReferences = references;
+ }
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
+ }
+ }
return result;
}
function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
@@ -82297,7 +83783,7 @@ var ts;
}
}
};
- var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator);
+ var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
if (!typeAcquisition) {
if (typingOptionstypeAcquisition) {
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
@@ -82332,6 +83818,7 @@ var ts;
return extendedConfigPath;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
+ var _a;
var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (sourceFile) {
(sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName);
@@ -82360,7 +83847,6 @@ var ts;
mapPropertiesInRawIfNotUndefined("files");
}
return extendedConfig;
- var _a;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
@@ -82385,7 +83871,7 @@ var ts;
}
ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
function getDefaultCompilerOptions(configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
+ var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
: {};
return options;
@@ -82393,10 +83879,13 @@ var ts;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultCompilerOptions(configFileName);
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
+ if (configFileName) {
+ options.configFilePath = ts.normalizeSlashes(configFileName);
+ }
return options;
}
function getDefaultTypeAcquisition(configFileName) {
- return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
+ return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultTypeAcquisition(configFileName);
@@ -82557,7 +84046,7 @@ var ts;
// or a recursive directory. This information is used by filesystem watchers to monitor for
// new entries in these paths.
var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
- var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
+ var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
}
/**
@@ -82591,37 +84080,41 @@ var ts;
if (filesSpecs) {
for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
var fileName = filesSpecs_1[_i];
- var file = ts.getNormalizedAbsolutePath(fileName, basePath);
- literalFileMap.set(keyMapper(file), file);
+ var file_13 = ts.getNormalizedAbsolutePath(fileName, basePath);
+ literalFileMap.set(keyMapper(file_13), file_13);
}
}
if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
- var file = _b[_a];
+ var file_14 = _b[_a];
// If we have already included a literal or wildcard path with a
// higher priority extension, we should skip this file.
//
// This handles cases where we may encounter both .ts and
// .d.ts (or .js if "allowJs" is enabled) in the same
// directory when they are compilation outputs.
- if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
+ if (hasFileWithHigherPriorityExtension(file_14, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
continue;
}
// We may have included a wildcard path with a lower priority
// extension due to the user-defined order of entries in the
// "include" array. If there is a lower priority extension in the
// same directory, we should remove it.
- removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
- var key = keyMapper(file);
+ removeWildcardFilesWithLowerPriorityExtension(file_14, wildcardFileMap, supportedExtensions, keyMapper);
+ var key = keyMapper(file_14);
if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
- wildcardFileMap.set(key, file);
+ wildcardFileMap.set(key, file_14);
}
}
}
var literalFiles = ts.arrayFrom(literalFileMap.values());
var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
+ var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) {
+ return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) });
+ });
return {
fileNames: literalFiles.concat(wildcardFiles),
+ projectReferences: projectReferences,
wildcardDirectories: wildcardDirectories,
spec: spec
};
@@ -82636,20 +84129,10 @@ var ts;
return diag === undefined;
});
function createDiagnostic(message, spec) {
- if (jsonSourceFile && jsonSourceFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) {
- var property = _a[_i];
- if (ts.isArrayLiteralExpression(property.initializer)) {
- for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) {
- var element = _c[_b];
- if (ts.isStringLiteral(element) && element.text === spec) {
- return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec);
- }
- }
- }
- }
- }
- return ts.createCompilerDiagnostic(message, spec);
+ var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
+ return element ?
+ ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
+ ts.createCompilerDiagnostic(message, spec);
}
}
function specToDiagnostic(spec, allowTrailingRecursion) {
@@ -82682,8 +84165,8 @@ var ts;
if (include !== undefined) {
var recursiveKeys = [];
for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
- var file = include_1[_i];
- var spec = ts.normalizePath(ts.combinePaths(path, file));
+ var file_15 = include_1[_i];
+ var spec = ts.normalizePath(ts.combinePaths(path, file_15));
if (excludeRegex && excludeRegex.test(spec)) {
continue;
}
@@ -82877,6 +84360,17 @@ var ts;
SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
})(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
+ var OutliningSpanKind;
+ (function (OutliningSpanKind) {
+ /** Single or multi-line comments */
+ OutliningSpanKind["Comment"] = "comment";
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ OutliningSpanKind["Region"] = "region";
+ /** Declarations and expressions */
+ OutliningSpanKind["Code"] = "code";
+ /** Contiguous blocks of import declarations */
+ OutliningSpanKind["Imports"] = "imports";
+ })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
var OutputFileType;
(function (OutputFileType) {
OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
@@ -82972,6 +84466,8 @@ var ts;
*
*/
ScriptElementKind["jsxAttribute"] = "JSX attribute";
+ /** String literal */
+ ScriptElementKind["string"] = "string";
})(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
var ScriptElementKindModifier;
(function (ScriptElementKindModifier) {
@@ -83077,7 +84573,7 @@ var ts;
case 236 /* TypeAliasDeclaration */:
case 165 /* TypeLiteral */:
return 2 /* Type */;
- case 292 /* JSDocTypedefTag */:
+ case 296 /* JSDocTypedefTag */:
// If it has no name node, it shares the name with the value declaration below it.
return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
case 272 /* EnumMember */:
@@ -83131,6 +84627,10 @@ var ts;
ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName
return 2 /* Type */;
}
+ else if (ts.isLiteralTypeNode(node.parent)) {
+ // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings.
+ return 2 /* Type */ | 1 /* Value */;
+ }
else {
return 1 /* Value */;
}
@@ -83193,6 +84693,8 @@ var ts;
switch (node.parent.kind) {
case 161 /* TypeReference */:
return true;
+ case 178 /* ImportType */:
+ return !node.parent.isTypeOf;
case 206 /* ExpressionWithTypeArguments */:
return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
}
@@ -83280,7 +84782,7 @@ var ts;
}
ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
function getContainerNode(node) {
- if (node.kind === 292 /* JSDocTypedefTag */) {
+ if (ts.isJSDocTypeAlias(node)) {
// This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
// node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
// Then we get parent again in the loop.
@@ -83318,7 +84820,10 @@ var ts;
case 204 /* ClassExpression */:
return "class" /* classElement */;
case 235 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
- case 236 /* TypeAliasDeclaration */: return "type" /* typeElement */;
+ case 236 /* TypeAliasDeclaration */:
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ return "type" /* typeElement */;
case 237 /* EnumDeclaration */: return "enum" /* enumElement */;
case 231 /* VariableDeclaration */:
return getKindOfVariableDeclaration(node);
@@ -83349,8 +84854,6 @@ var ts;
case 251 /* ExportSpecifier */:
case 245 /* NamespaceImport */:
return "alias" /* alias */;
- case 292 /* JSDocTypedefTag */:
- return "type" /* typeElement */;
case 199 /* BinaryExpression */:
var kind = ts.getSpecialPropertyAssignmentKind(node);
var right = node.right;
@@ -83412,6 +84915,10 @@ var ts;
return startEndContainsRange(r1.pos, r1.end, r2);
}
ts.rangeContainsRange = rangeContainsRange;
+ function rangeContainsPosition(r, pos) {
+ return r.pos <= pos && pos <= r.end;
+ }
+ ts.rangeContainsPosition = rangeContainsPosition;
function startEndContainsRange(start, end, range) {
return start <= range.pos && end >= range.end;
}
@@ -83678,7 +85185,7 @@ var ts;
return findPrecedingToken(position, file);
}
ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
- function findNextToken(previousToken, parent) {
+ function findNextToken(previousToken, parent, sourceFile) {
return find(parent);
function find(n) {
if (ts.isToken(n) && n.pos === previousToken.end) {
@@ -83693,7 +85200,7 @@ var ts;
(child.pos <= previousToken.pos && child.end > previousToken.end) ||
// previous token ends exactly at the beginning of child
(child.pos === previousToken.end);
- if (shouldDiveInChildNode && nodeHasTokens(child)) {
+ if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) {
return find(child);
}
}
@@ -83724,11 +85231,11 @@ var ts;
if (position < child.end) {
var start = child.getStart(sourceFile, includeJsDoc);
var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
- !nodeHasTokens(child) ||
+ !nodeHasTokens(child, sourceFile) ||
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
else {
@@ -83743,7 +85250,7 @@ var ts;
// Try to find the rightmost token in the file without filtering.
// Namely we are skipping the check: 'position < node.end'
if (children.length) {
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
}
@@ -83757,19 +85264,19 @@ var ts;
return n;
}
var children = n.getChildren(sourceFile);
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
/**
* Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
*/
- function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) {
+ function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
var child = children[i];
if (isWhiteSpaceOnlyJsxText(child)) {
ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
}
- else if (nodeHasTokens(children[i])) {
+ else if (nodeHasTokens(children[i], sourceFile)) {
return children[i];
}
}
@@ -83881,22 +85388,22 @@ var ts;
remainingLessThanTokens++;
break;
case 18 /* CloseBraceToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile);
if (!token)
return false;
break;
case 20 /* CloseParenToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile);
if (!token)
return false;
break;
case 22 /* CloseBracketToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile);
if (!token)
return false;
@@ -83950,10 +85457,10 @@ var ts;
}
}
ts.hasDocComment = hasDocComment;
- function nodeHasTokens(n) {
+ function nodeHasTokens(n, sourceFile) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note: getWidth() does not take trivia into account.
- return n.getWidth() !== 0;
+ return n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node) {
var flags = ts.getCombinedModifierFlags(node);
@@ -84050,11 +85557,6 @@ var ts;
return false;
}
ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
- function hasTrailingDirectorySeparator(path) {
- var lastCharacter = path.charAt(path.length - 1);
- return lastCharacter === "/" || lastCharacter === "\\";
- }
- ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function isInReferenceComment(sourceFile, position) {
return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) {
var commentText = sourceFile.text.substring(c.pos, c.end);
@@ -84077,6 +85579,10 @@ var ts;
return ts.createTextSpanFromBounds(range.pos, range.end);
}
ts.createTextSpanFromRange = createTextSpanFromRange;
+ function createTextRangeFromSpan(span) {
+ return ts.createTextRange(span.start, span.start + span.length);
+ }
+ ts.createTextRangeFromSpan = createTextRangeFromSpan;
function createTextChangeFromStartLength(start, length, newText) {
return createTextChange(ts.createTextSpan(start, length), newText);
}
@@ -84109,7 +85615,6 @@ var ts;
return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
}
ts.isExternalModuleSymbol = isExternalModuleSymbol;
- /** Returns `true` the first time it encounters a node and `false` afterwards. */
function nodeSeenTracker() {
var seen = [];
return function (node) {
@@ -84157,6 +85662,63 @@ var ts;
return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
}
ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
+ function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) {
+ return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined;
+ }
+ ts.makeImportIfNecessary = makeImportIfNecessary;
+ function makeImport(defaultImport, namedImports, moduleSpecifier) {
+ return ts.createImportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, defaultImport || namedImports
+ ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined)
+ : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier);
+ }
+ ts.makeImport = makeImport;
+ function symbolNameNoDefault(symbol) {
+ var escaped = symbolEscapedNameNoDefault(symbol);
+ return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
+ }
+ ts.symbolNameNoDefault = symbolNameNoDefault;
+ function symbolEscapedNameNoDefault(symbol) {
+ if (symbol.escapedName !== "default" /* Default */) {
+ return symbol.escapedName;
+ }
+ return ts.firstDefined(symbol.declarations, function (decl) {
+ var name = ts.getNameOfDeclaration(decl);
+ return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined;
+ });
+ }
+ ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
+ function getPropertySymbolFromBindingElement(checker, bindingElement) {
+ var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
+ var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
+ if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
+ // See GH#16922
+ ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
+ return propSymbol.target;
+ }
+ return propSymbol;
+ }
+ ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
+ var NodeSet = /** @class */ (function () {
+ function NodeSet() {
+ this.map = ts.createMap();
+ }
+ NodeSet.prototype.add = function (node) {
+ this.map.set(String(ts.getNodeId(node)), node);
+ };
+ NodeSet.prototype.has = function (node) {
+ return this.map.has(String(ts.getNodeId(node)));
+ };
+ NodeSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ NodeSet.prototype.some = function (pred) {
+ return ts.forEachEntry(this.map, pred) || false;
+ };
+ return NodeSet;
+ }());
+ ts.NodeSet = NodeSet;
})(ts || (ts = {}));
// Display-part writer helpers
/* @internal */
@@ -84489,20 +86051,20 @@ var ts;
* user was before extracting it.
*/
/* @internal */
- function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) {
+ function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
var delta = 0;
var lastPos = -1;
for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
- var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
+ var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
ts.Debug.assert(fileName === renameFilename);
- for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) {
- var change = textChanges_2[_b];
+ for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
+ var change = textChanges_1[_b];
var span = change.span, newText = change.newText;
var index = newText.indexOf(name);
if (index !== -1) {
lastPos = span.start + delta + index;
// If the reference comes first, return immediately.
- if (!isDeclaredBeforeUse) {
+ if (!preferLastLocation) {
return lastPos;
}
}
@@ -84510,7 +86072,7 @@ var ts;
}
}
// If the declaration comes first, return the position of the last occurrence.
- ts.Debug.assert(isDeclaredBeforeUse);
+ ts.Debug.assert(preferLastLocation);
ts.Debug.assert(lastPos >= 0);
return lastPos;
}
@@ -85158,20 +86720,22 @@ 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 288 /* JSDocParameterTag */:
+ case 292 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
+ pos = tag.end;
break;
- case 290 /* JSDocTypeTag */:
+ case 294 /* JSDocTypeTag */:
processElement(tag.typeExpression);
+ pos = tag.end;
break;
- case 289 /* JSDocReturnTag */:
+ case 293 /* JSDocReturnTag */:
processElement(tag.typeExpression);
+ pos = tag.end;
break;
}
- pos = tag.end;
}
}
if (pos !== docComment.end) {
@@ -85413,7 +86977,7 @@ var ts;
var scriptPath = node.getSourceFile().path;
var scriptDirectory = ts.getDirectoryPath(scriptPath);
if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) {
- var extensions = ts.getSupportedExtensions(compilerOptions);
+ var extensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (compilerOptions.rootDirs) {
return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath);
}
@@ -85426,6 +86990,12 @@ var ts;
return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
}
}
+ function getSupportedExtensionsForModuleResolution(compilerOptions) {
+ var extensions = ts.getSupportedExtensions(compilerOptions);
+ return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
+ extensions.concat(".json" /* Json */) :
+ extensions;
+ }
/**
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
@@ -85464,13 +87034,16 @@ var ts;
* Remove the basename from the path. Note that we don't use the basename to filter completions;
* the client is responsible for refining completions.
*/
- fragment = ts.getDirectoryPath(fragment);
+ if (!ts.hasTrailingDirectorySeparator(fragment)) {
+ fragment = ts.getDirectoryPath(fragment);
+ }
if (fragment === "") {
fragment = "." + ts.directorySeparator;
}
fragment = ts.ensureTrailingDirectorySeparator(fragment);
- var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment));
- var baseDirectory = ts.getDirectoryPath(absolutePath);
+ // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
+ var absolutePath = ts.resolvePath(scriptPath, fragment);
+ var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
if (tryDirectoryExists(host, baseDirectory)) {
// Enumerate the available files if possible
@@ -85489,7 +87062,7 @@ var ts;
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
}
- var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
+ var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
if (!foundFiles.has(foundFileName)) {
foundFiles.set(foundFileName, true);
}
@@ -85502,8 +87075,8 @@ var ts;
var directories = tryGetDirectories(host, baseDirectory);
if (directories) {
for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) {
- var directory = directories_1[_a];
- var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
+ var directory_2 = directories_1[_a];
+ var directoryName = ts.getBaseFileName(ts.normalizePath(directory_2));
if (directoryName !== "@types") {
result.push(nameAndKind(directoryName, "directory" /* directory */));
}
@@ -85522,7 +87095,7 @@ var ts;
function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
var result = [];
- var fileExtensions = ts.getSupportedExtensions(compilerOptions);
+ var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (baseUrl) {
var projectDir = compilerOptions.project || host.getCurrentDirectory();
var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl);
@@ -85530,7 +87103,7 @@ var ts;
for (var path in paths) {
var patterns = paths[path];
if (paths.hasOwnProperty(path) && patterns) {
- var _loop_10 = function (name, kind) {
+ var _loop_12 = function (name, kind) {
// Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
if (!result.some(function (entry) { return entry.name === name; })) {
result.push(nameAndKind(name, kind));
@@ -85538,12 +87111,12 @@ var ts;
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind;
- _loop_10(name, kind);
+ _loop_12(name, kind);
}
}
}
}
- var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined;
+ var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) {
var ambientName = _d[_c];
result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */));
@@ -85554,7 +87127,7 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_11 = function (moduleName) {
+ var _loop_13 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */));
@@ -85562,7 +87135,7 @@ var ts;
};
for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) {
var moduleName = _f[_e];
- _loop_11(moduleName);
+ _loop_13(moduleName);
}
}
if (!foundGlobal) {
@@ -85598,12 +87171,13 @@ var ts;
}
// The prefix has two effective parts: the directory path and the base component after the filepath that is not a
// full directory component. For example: directory/path/of/prefix/base*
- var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix);
- var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix);
- var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix);
+ var normalizedPrefix = ts.resolvePath(parsed.prefix);
+ var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
+ var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
var fragmentHasPath = containsSlash(fragment);
+ var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
// Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
- var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory;
+ var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
var normalizedSuffix = ts.normalizePath(parsed.suffix);
// Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
@@ -85764,15 +87338,6 @@ var ts;
}
return false;
}
- function normalizeAndPreserveTrailingSlash(path) {
- if (ts.normalizeSlashes(path) === "./") {
- // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case.
- // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning.
- return "";
- }
- var norm = ts.normalizePath(path);
- return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm;
- }
/**
* Matches a triple slash reference directive with an incomplete string literal for its path. Used
* to determine if the caret is currently within the string literal and capture the literal fragment
@@ -85892,7 +87457,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
- var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); });
+ var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); });
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
}
default:
@@ -86459,11 +88024,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 277 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 293 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 297 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -86599,12 +88164,8 @@ var ts;
}
else if (isRightOfOpenTag) {
var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
- if (tryGetGlobalSymbols()) {
- symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); }));
- }
- else {
- symbols = tagSymbols;
- }
+ tryGetGlobalSymbols();
+ symbols = tagSymbols.concat(symbols);
completionKind = 3 /* MemberLike */;
}
else if (isStartingCloseTag) {
@@ -86628,11 +88189,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
- case 289 /* JSDocReturnTag */:
- case 290 /* JSDocTypeTag */:
- case 292 /* JSDocTypedefTag */:
+ case 292 /* JSDocParameterTag */:
+ case 297 /* JSDocPropertyTag */:
+ case 293 /* JSDocReturnTag */:
+ case 294 /* JSDocTypeTag */:
+ case 296 /* JSDocTypedefTag */:
return true;
}
}
@@ -86894,7 +88455,7 @@ var ts;
var exportedSymbols = typeChecker.getExportsOfModule(symbol);
// If the exported symbols contains type,
// symbol can be referenced at locations where type is allowed
- return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation);
+ return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation);
}
}
function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) {
@@ -87670,7 +89231,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 294 /* SyntaxList */:
+ case 298 /* 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);
@@ -87707,6 +89268,9 @@ var ts;
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
switch (triggerCharacter) {
+ case ".":
+ case "@":
+ return true;
case '"':
case "'":
case "`":
@@ -87715,8 +89279,12 @@ var ts;
case "<":
// Opening JSX tag
return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */;
+ case "/":
+ return ts.isStringLiteralLike(contextToken)
+ ? !!ts.tryGetImportFromModuleSpecifier(contextToken)
+ : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent);
default:
- return ts.Debug.fail(triggerCharacter);
+ return ts.Debug.assertNever(triggerCharacter);
}
}
function isStringLiteralOrTemplate(node) {
@@ -87811,6 +89379,10 @@ var ts;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]);
+ case 121 /* AwaitKeyword */:
+ return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
+ case 120 /* AsyncKeyword */:
+ return highlightSpans(getAsyncAndAwaitOccurrences(node));
default:
return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
? highlightSpans(getModifierOccurrences(node.kind, node.parent))
@@ -88058,6 +89630,29 @@ var ts;
});
return keywords;
}
+ function getAsyncAndAwaitOccurrences(node) {
+ var func = ts.getContainingFunction(node);
+ if (!func) {
+ return undefined;
+ }
+ var keywords = [];
+ if (func.modifiers) {
+ func.modifiers.forEach(function (modifier) {
+ pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */);
+ });
+ }
+ ts.forEachChild(func, aggregate);
+ return keywords;
+ function aggregate(node) {
+ if (ts.isAwaitExpression(node)) {
+ pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */);
+ }
+ // Do not cross function boundaries.
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
+ ts.forEachChild(node, aggregate);
+ }
+ }
+ }
function getIfElseOccurrences(ifStatement, sourceFile) {
var keywords = getIfElseKeywords(ifStatement, sourceFile);
var result = [];
@@ -88178,9 +89773,10 @@ var ts;
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
+ var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target;
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
- var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind);
+ var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
entry = {
sourceFile: sourceFile,
languageServiceRefCount: 1,
@@ -88309,6 +89905,8 @@ var ts;
addIndirectUser(direct.getSourceFile());
}
break;
+ case 71 /* Identifier */: // for 'const x = require("y");
+ break; // TODO: GH#23879
case 242 /* ImportEqualsDeclaration */:
handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */));
break;
@@ -88338,6 +89936,11 @@ var ts;
directImports.push(direct);
}
break;
+ case 178 /* ImportType */:
+ directImports.push(direct);
+ break;
+ default:
+ ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct));
}
}
}
@@ -88415,6 +90018,14 @@ var ts;
return;
}
if (decl.kind === 178 /* ImportType */) {
+ if (decl.qualifier) {
+ if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) {
+ singleReferences.push(decl.qualifier);
+ }
+ }
+ else if (exportKind === 2 /* ExportEquals */) {
+ singleReferences.push(decl.argument.literal);
+ }
return;
}
// Ignore if there's a grammar error
@@ -88442,7 +90053,7 @@ var ts;
var name = importClause.name;
// If a default import has the same name as the default export, allow to rename it.
// Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
- if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) {
+ if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
var defaultImportAlias = checker.getSymbolAtLocation(name);
addSearch(name, defaultImportAlias);
}
@@ -88500,24 +90111,18 @@ var ts;
function findNamespaceReExports(sourceFileLike, name, checker) {
var namespaceImportSymbol = checker.getSymbolAtLocation(name);
return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
- if (statement.kind !== 249 /* ExportDeclaration */)
+ if (!ts.isExportDeclaration(statement))
return;
- var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier;
- if (moduleSpecifier || !exportClause)
- return;
- for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) {
- var element = _b[_i];
- if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) {
- return true;
- }
- }
+ var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
+ return !moduleSpecifier && exportClause &&
+ exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
});
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var referencingFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var referencingFile = sourceFiles_5[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === 273 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
@@ -88547,8 +90152,8 @@ var ts;
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
var map = ts.createMap();
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
@@ -88653,6 +90258,9 @@ var ts;
else if (ts.isBinaryExpression(parent.parent)) {
return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true);
}
+ else if (ts.isJSDocTypedefTag(parent)) {
+ return exportInfo(symbol, 0 /* Named */);
+ }
}
function getExportAssignmentExport(ex) {
// Get the symbol for the `export =` node; its parent is the module it's the export of.
@@ -88697,7 +90305,7 @@ var ts;
// If the import has a different name than the export, do not continue searching.
// If `importedName` is undefined, do continue searching as the export is anonymous.
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
- var importedName = symbolName(importedSymbol);
+ var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
}
@@ -88764,15 +90372,6 @@ var ts;
return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
}
FindAllReferences.getExportInfo = getExportInfo;
- function symbolName(symbol) {
- if (symbol.escapedName !== "default" /* Default */) {
- return symbol.escapedName;
- }
- return ts.forEach(symbol.declarations, function (decl) {
- var name = ts.getNameOfDeclaration(decl);
- return name && name.kind === 71 /* Identifier */ && name.escapedText;
- });
- }
/** If at an export specifier, go to the symbol it refers to. */
function skipExportSpecifierSymbol(symbol, checker) {
// For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
@@ -88847,9 +90446,9 @@ var ts;
// 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 === 270 /* ShorthandPropertyAssignment */) {
- var result_4 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); });
- return result_4;
+ var result_5 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); });
+ return result_5;
}
else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -88882,8 +90481,8 @@ var ts;
case "symbol": {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ var name_3 = displayParts_1.map(function (p) { return p.text; }).join("");
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 };
}
case "label": {
var node_3 = def.node;
@@ -88891,13 +90490,13 @@ var ts;
}
case "keyword": {
var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var name_4 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] };
}
case "this": {
var node_5 = def.node;
var symbol = checker.getSymbolAtLocation(node_5);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case "string": {
@@ -89010,7 +90609,7 @@ var ts;
if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); }
if (ts.isSourceFile(node)) {
var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program);
- return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles, sourceFilesSet);
+ return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
}
if (!options.implementations) {
var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
@@ -89025,32 +90624,36 @@ var ts;
// String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined;
}
- if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) {
- return getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet);
+ var moduleReferences = ts.emptyArray;
+ var moduleSourceFile = isModuleSymbol(symbol);
+ if (moduleSourceFile) {
+ var exportEquals = symbol.exports.get("export=" /* ExportEquals */);
+ // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
+ moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
+ if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName))
+ return moduleReferences;
+ // Continue to get references to 'export ='.
+ symbol = ts.skipAlias(exportEquals, checker);
+ node = undefined;
}
- return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
+ return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
}
Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
- function isModuleReferenceLocation(node) {
- if (!ts.isStringLiteralLike(node)) {
- return false;
- }
- switch (node.parent.kind) {
- case 238 /* ModuleDeclaration */:
- case 253 /* ExternalModuleReference */:
- case 243 /* ImportDeclaration */:
- case 249 /* ExportDeclaration */:
- return true;
- case 186 /* CallExpression */:
- return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent);
- default:
- return false;
- }
+ function isModuleSymbol(symbol) {
+ return symbol.flags & 1536 /* Module */ && ts.find(symbol.declarations, ts.isSourceFile);
}
- function getReferencedSymbolsForModule(program, symbol, sourceFiles, sourceFilesSet) {
+ function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) {
ts.Debug.assert(!!symbol.valueDeclaration);
- var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) {
+ var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) {
if (reference.kind === "import") {
+ var parent = reference.literal.parent;
+ if (ts.isLiteralTypeNode(parent)) {
+ var importType = ts.cast(parent.parent, ts.isImportTypeNode);
+ if (excludeImportTypeOfExportEquals && !importType.qualifier) {
+ return undefined;
+ }
+ }
+ // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway.
return { type: "node", node: reference.literal };
}
else {
@@ -89073,10 +90676,11 @@ var ts;
}
break;
default:
+ // This may be merged with something.
ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
- return [{ definition: { type: "symbol", symbol: symbol }, references: references }];
+ return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray;
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
@@ -89104,17 +90708,17 @@ var ts;
}
/** Core find-all-references algorithm for a normal symbol. */
function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) {
- symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
+ symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol;
// Compute the meaning from the location and the symbol it references
- var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol);
+ var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */;
var result = [];
- var state = new State(sourceFiles, sourceFilesSet, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result);
- if (node.kind === 79 /* DefaultKeyword */) {
+ var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result);
+ if (node && node.kind === 79 /* DefaultKeyword */) {
addReference(node, symbol, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state);
}
else {
- var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) });
+ var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.implementations) : [symbol] });
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
var scope = getSymbolScope(symbol);
@@ -89160,7 +90764,6 @@ var ts;
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
- ts.Debug.assert(decl.kind === 273 /* SourceFile */);
ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol));
}
return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
@@ -89234,7 +90837,7 @@ var ts;
// here appears to be intentional).
var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b;
var escapedText = ts.escapeLeadingUnderscores(text);
- var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
+ var parents = this.options.implementations && location && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } };
};
/**
@@ -89278,10 +90881,8 @@ var ts;
var addRef = state.referenceAdder(exportSymbol);
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
- // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
+ if (shouldAddSingleReference(singleRef, state))
addRef(singleRef);
- }
}
}
// For each import, find all references to that import in its source file.
@@ -89310,6 +90911,17 @@ var ts;
}
}
}
+ function shouldAddSingleReference(singleRef, state) {
+ if (!hasMatchingMeaning(singleRef, state))
+ return false;
+ if (!state.options.isForRename)
+ return true;
+ // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;`
+ if (!ts.isIdentifier(singleRef))
+ return false;
+ // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
+ return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */);
+ }
// Go to the symbol we imported from and find references for it.
function searchForImportedSymbol(symbol, state) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -89333,22 +90945,14 @@ var ts;
var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */);
if (bindingElement &&
bindingElement.parent.kind === 179 /* ObjectBindingPattern */ &&
+ ts.isIdentifier(bindingElement.name) &&
!bindingElement.propertyName) {
return bindingElement;
}
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
var bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
- if (!bindingElement)
- return undefined;
- var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
- var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
- if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
- // See GH#16922
- ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
- return propSymbol.target;
- }
- return propSymbol;
+ return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement);
}
/**
* Determines the smallest scope in which a symbol may have named references.
@@ -89519,6 +91123,9 @@ var ts;
getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
}
}
+ function hasMatchingMeaning(referenceLocation, state) {
+ return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
+ }
function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
@@ -89534,9 +91141,8 @@ var ts;
}
return;
}
- if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
+ if (!hasMatchingMeaning(referenceLocation, state))
return;
- }
var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
if (!referenceSymbol) {
return;
@@ -90197,7 +91803,9 @@ var ts;
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.
- return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; })
+ return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) ||
+ // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias
+ symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })
? [sigInfo]
: [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node));
}
@@ -90252,14 +91860,14 @@ var ts;
function getReferenceAtPosition(sourceFile, position, program) {
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
if (referencePath) {
- var file = ts.tryResolveScriptReference(program, sourceFile, referencePath);
- return file && { fileName: referencePath.fileName, file: file };
+ var file_16 = ts.tryResolveScriptReference(program, sourceFile, referencePath);
+ return file_16 && { fileName: referencePath.fileName, file: file_16 };
}
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
- var file = reference && program.getSourceFile(reference.resolvedFileName);
- return file && { fileName: typeReferenceDirective.fileName, file: file };
+ var file_17 = reference && program.getSourceFile(reference.resolvedFileName);
+ return file_17 && { fileName: typeReferenceDirective.fileName, file: file_17 };
}
return undefined;
}
@@ -90431,6 +92039,7 @@ var ts;
"author",
"argument",
"borrows",
+ "callback",
"class",
"constant",
"constructor",
@@ -90495,10 +92104,12 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 293 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
+ case 297 /* JSDocPropertyTag */:
return [declaration];
- case 292 /* JSDocTypedefTag */:
- return [declaration.parent];
+ case 291 /* JSDocCallbackTag */:
+ case 296 /* JSDocTypedefTag */:
+ return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
}
@@ -90518,15 +92129,16 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 286 /* JSDocAugmentsTag */:
+ case 289 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 291 /* JSDocTemplateTag */:
+ case 295 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 290 /* JSDocTypeTag */:
+ case 294 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 292 /* JSDocTypedefTag */:
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
+ case 297 /* JSDocPropertyTag */:
+ case 292 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -90851,12 +92463,42 @@ var ts;
JsTyping.isTypingUpToDate = isTypingUpToDate;
/* @internal */
JsTyping.nodeCoreModuleList = [
- "buffer", "querystring", "events", "http", "cluster",
- "zlib", "os", "https", "punycode", "repl", "readline",
- "vm", "child_process", "url", "dns", "net",
- "dgram", "fs", "path", "string_decoder", "tls",
- "crypto", "stream", "util", "assert", "tty", "domain",
- "constants", "process", "v8", "timers", "console"
+ "assert",
+ "async_hooks",
+ "buffer",
+ "child_process",
+ "cluster",
+ "console",
+ "constants",
+ "crypto",
+ "dgram",
+ "dns",
+ "domain",
+ "events",
+ "fs",
+ "http",
+ "https",
+ "http2",
+ "inspector",
+ "net",
+ "os",
+ "path",
+ "perf_hooks",
+ "process",
+ "punycode",
+ "querystring",
+ "readline",
+ "repl",
+ "stream",
+ "string_decoder",
+ "timers",
+ "tls",
+ "tty",
+ "url",
+ "util",
+ "v8",
+ "vm",
+ "zlib"
];
/* @internal */
JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
@@ -90915,8 +92557,8 @@ var ts;
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
- var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
- addInferredTypings(module, "Inferred typings from unresolved imports");
+ var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ addInferredTypings(module_1, "Inferred typings from unresolved imports");
}
// Add the cached typing locations for inferred typings that are already installed
packageNameToTypingLocation.forEach(function (typing, name) {
@@ -91013,8 +92655,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_5.config;
+ var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_6.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
@@ -91114,7 +92756,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_12 = function (sourceFile) {
+ var _loop_14 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) {
return "continue";
@@ -91124,9 +92766,9 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_12(sourceFile);
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var sourceFile = sourceFiles_7[_i];
+ _loop_14(sourceFile);
}
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
@@ -91503,7 +93145,7 @@ var ts;
if (ts.hasJSDocNodes(node)) {
ts.forEach(node.jsDoc, function (jsDoc) {
ts.forEach(jsDoc.tags, function (tag) {
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (ts.isJSDocTypeAlias(tag)) {
addLeafNode(tag);
}
});
@@ -91578,6 +93220,7 @@ var ts;
}
/** Merge source into target. Source should be thrown away after this is called. */
function merge(target, source) {
+ var _a;
target.additionalNodes = target.additionalNodes || [];
target.additionalNodes.push(source.node);
if (source.additionalNodes) {
@@ -91588,7 +93231,6 @@ var ts;
mergeChildren(target.children);
sortChildren(target.children);
}
- var _a;
}
/** Recursively ensure that each NavNode's children are in sorted order. */
function sortChildren(children) {
@@ -91616,8 +93258,6 @@ var ts;
case 192 /* ArrowFunction */:
case 204 /* ClassExpression */:
return getFunctionOrClassName(node);
- case 292 /* JSDocTypedefTag */:
- return getJSDocTypedefTagName(node);
default:
return undefined;
}
@@ -91659,29 +93299,10 @@ var ts;
return "()";
case 159 /* IndexSignature */:
return "[]";
- case 292 /* JSDocTypedefTag */:
- return getJSDocTypedefTagName(node);
default:
return "";
}
}
- function getJSDocTypedefTagName(node) {
- if (node.name) {
- return node.name.text;
- }
- else {
- var parentNode = node.parent && node.parent.parent;
- if (parentNode && parentNode.kind === 213 /* VariableStatement */) {
- if (parentNode.declarationList.declarations.length > 0) {
- var nameIdentifier = parentNode.declarationList.declarations[0].name;
- if (nameIdentifier.kind === 71 /* Identifier */) {
- return nameIdentifier.text;
- }
- }
- }
- return "";
- }
- }
/** Flattens the NavNode tree to a list, keeping only the top-level items. */
function topLevelItems(root) {
var topLevel = [];
@@ -91707,7 +93328,8 @@ var ts;
case 238 /* ModuleDeclaration */:
case 273 /* SourceFile */:
case 236 /* TypeAliasDeclaration */:
- case 292 /* JSDocTypedefTag */:
+ case 296 /* JSDocTypedefTag */:
+ case 291 /* JSDocCallbackTag */:
return true;
case 154 /* Constructor */:
case 153 /* MethodDeclaration */:
@@ -91870,17 +93492,23 @@ var ts;
*/
function organizeImports(sourceFile, formatContext, host, program, _preferences) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
+ var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
// All of the old ImportDeclarations in the file, in syntactic order.
var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
- organizeImportsWorker(topLevelImportDecls);
+ organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
+ // All of the old ExportDeclarations in the file, in syntactic order.
+ var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
+ organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
var ambientModule = _a[_i];
var ambientModuleBody = getModuleBlock(ambientModule);
var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
- organizeImportsWorker(ambientModuleImportDecls);
+ organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
+ var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
+ organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
- function organizeImportsWorker(oldImportDecls) {
+ function organizeImportsWorker(oldImportDecls, coalesce) {
if (ts.length(oldImportDecls) === 0) {
return;
}
@@ -91894,7 +93522,7 @@ var ts;
var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
return getExternalModuleName(importGroup[0].moduleSpecifier)
- ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
+ ? coalesce(importGroup)
: importGroup;
});
// Delete or replace the first import.
@@ -91969,7 +93597,9 @@ var ts;
}
}
function getExternalModuleName(specifier) {
- return ts.isStringLiteralLike(specifier) ? specifier.text : undefined;
+ return specifier !== undefined && ts.isStringLiteralLike(specifier)
+ ? specifier.text
+ : undefined;
}
/* @internal */ // Internal for testing
/**
@@ -92015,15 +93645,14 @@ var ts;
}
}
newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
- var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
- return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
- compareIdentifiers(s1.name, s2.name);
- });
+ var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
var importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
var newNamedImports = sortedImportSpecifiers.length === 0
- ? undefined
+ ? newDefaultImport
+ ? undefined
+ : ts.createNamedImports(ts.emptyArray)
: namedImports.length === 0
? ts.createNamedImports(sortedImportSpecifiers)
: ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers);
@@ -92069,23 +93698,77 @@ var ts;
namedImports: namedImports,
};
}
- function compareIdentifiers(s1, s2) {
- return ts.compareStringsCaseSensitive(s1.text, s2.text);
- }
}
OrganizeImports.coalesceImports = coalesceImports;
+ /* @internal */ // Internal for testing
+ /**
+ * @param exportGroup a list of ExportDeclarations, all with the same module name.
+ */
+ function coalesceExports(exportGroup) {
+ if (exportGroup.length === 0) {
+ return exportGroup;
+ }
+ var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
+ var coalescedExports = [];
+ if (exportWithoutClause) {
+ coalescedExports.push(exportWithoutClause);
+ }
+ if (namedExports.length === 0) {
+ return coalescedExports;
+ }
+ var newExportSpecifiers = [];
+ newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
+ var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
+ var exportDecl = namedExports[0];
+ coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
+ return coalescedExports;
+ /*
+ * Returns entire export declarations because they may already have been rewritten and
+ * may lack parent pointers. The desired parts can easily be recovered based on the
+ * categorization.
+ */
+ function getCategorizedExports(exportGroup) {
+ var exportWithoutClause;
+ var namedExports = [];
+ for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
+ var exportDeclaration = exportGroup_1[_i];
+ if (exportDeclaration.exportClause === undefined) {
+ // Only the first such export is interesting - the others are redundant.
+ // Note: Unfortunately, we will lose trivia that was on this node.
+ exportWithoutClause = exportWithoutClause || exportDeclaration;
+ }
+ else {
+ namedExports.push(exportDeclaration);
+ }
+ }
+ return {
+ exportWithoutClause: exportWithoutClause,
+ namedExports: namedExports,
+ };
+ }
+ }
+ OrganizeImports.coalesceExports = coalesceExports;
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
}
+ function sortSpecifiers(specifiers) {
+ return ts.stableSort(specifiers, function (s1, s2) {
+ return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
+ compareIdentifiers(s1.name, s2.name);
+ });
+ }
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
var name2 = getExternalModuleName(m2);
return ts.compareBooleans(name1 === undefined, name2 === undefined) ||
ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) ||
- ts.compareStringsCaseSensitive(name1, name2);
+ ts.compareStringsCaseInsensitive(name1, name2);
}
OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
+ function compareIdentifiers(s1, s2) {
+ return ts.compareStringsCaseInsensitive(s1.text, s2.text);
+ }
})(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
})(ts || (ts = {}));
/* @internal */
@@ -92095,7 +93778,7 @@ var ts;
var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
- for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate;
var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
@@ -92107,25 +93790,16 @@ var ts;
}
ts.getEditsForFileRename = getEditsForFileRename;
function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) {
- var cfg = program.getCompilerOptions().configFile;
- if (!cfg)
- return;
- var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath);
+ var configFile = program.getCompilerOptions().configFile;
+ var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath);
if (oldFile) {
- changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath);
+ changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath);
}
}
- function getFilesEntry(cfg, fileName) {
- var filesProp = ts.find(cfg.properties, function (prop) {
- return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
- });
- var files = filesProp && filesProp.initializer;
- return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined;
- }
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
- function getImportsToUpdate(program, oldFilePath) {
+ function getImportsToUpdate(program, oldFilePath, host) {
var checker = program.getTypeChecker();
var result = [];
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
@@ -92141,8 +93815,10 @@ var ts;
// If it resolved to something already, ignore.
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
- var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
- if (ts.contains(resolved.failedLookupLocations, oldFilePath)) {
+ var resolved = host.resolveModuleNames
+ ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
+ : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
+ if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
}
@@ -92151,11 +93827,11 @@ var ts;
}
function getPathUpdater(oldFilePath, newFilePath, host) {
// Get the relative path from old to new location, and append it on to the end of imports and normalize.
- var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
+ var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
return function (oldPath) {
if (!ts.pathIsRelative(oldPath))
return;
- return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
+ return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
};
}
function createStringRange(node, sourceFile) {
@@ -92176,7 +93852,27 @@ var ts;
OutliningElementsCollector.collectElements = collectElements;
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
var depthRemaining = 40;
- sourceFile.forEachChild(function walk(n) {
+ var current = 0;
+ var statements = sourceFile.statements;
+ var n = statements.length;
+ while (current < n) {
+ while (current < n && !ts.isAnyImportSyntax(statements[current])) {
+ visitNonImportNode(statements[current]);
+ current++;
+ }
+ if (current === n)
+ break;
+ var firstImport = current;
+ while (current < n && ts.isAnyImportSyntax(statements[current])) {
+ addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
+ current++;
+ }
+ var lastImport = current - 1;
+ if (lastImport !== firstImport) {
+ out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
+ }
+ }
+ function visitNonImportNode(n) {
if (depthRemaining === 0)
return;
cancellationToken.throwIfCancellationRequested();
@@ -92189,17 +93885,17 @@ var ts;
depthRemaining--;
if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
// Consider an 'else if' to be on the same depth as the 'if'.
- walk(n.expression);
- walk(n.thenStatement);
+ visitNonImportNode(n.expression);
+ visitNonImportNode(n.thenStatement);
depthRemaining++;
- walk(n.elseStatement);
+ visitNonImportNode(n.elseStatement);
depthRemaining--;
}
else {
- n.forEachChild(walk);
+ n.forEachChild(visitNonImportNode);
}
depthRemaining++;
- });
+ }
}
function addRegionOutliningSpans(sourceFile, out) {
var regions = [];
@@ -92214,7 +93910,7 @@ var ts;
}
if (!result[1]) {
var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region"));
+ regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -92248,7 +93944,7 @@ var ts;
break;
case 3 /* MultiLineCommentTrivia */:
combineAndAddMultipleSingleLineComments();
- out.push(createOutliningSpanFromBounds(pos, end));
+ out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
singleLineCommentCount = 0;
break;
default:
@@ -92259,12 +93955,12 @@ var ts;
function combineAndAddMultipleSingleLineComments() {
// Only outline spans of two or more consecutive single line comments
if (singleLineCommentCount > 1) {
- out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd));
+ out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
}
}
}
- function createOutliningSpanFromBounds(pos, end) {
- return createOutliningSpan(ts.createTextSpanFromBounds(pos, end));
+ function createOutliningSpanFromBounds(pos, end, kind) {
+ return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
switch (n.kind) {
@@ -92298,7 +93994,7 @@ var ts;
default:
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
- return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile));
+ return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
}
case 239 /* ModuleBlock */:
return spanForNode(n.parent);
@@ -92330,14 +94026,14 @@ var ts;
return undefined;
}
var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
- return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
+ return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
}
- function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) {
+ function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
if (hintSpan === void 0) { hintSpan = textSpan; }
if (autoCollapse === void 0) { autoCollapse = false; }
if (bannerText === void 0) { bannerText = "..."; }
- return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
+ return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
}
})(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
})(ts || (ts = {}));
@@ -92620,13 +94316,13 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_13 = function (start) {
+ var _loop_15 = function (start) {
if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
return { value: start };
}
};
for (var start = 0; start <= n; start++) {
- var state_4 = _loop_13(start);
+ var state_4 = _loop_15(start);
if (typeof state_4 === "object")
return state_4.value;
}
@@ -93172,6 +94868,9 @@ var ts;
if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) {
return undefined;
}
+ // Can't rename a module name.
+ if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node))
+ return undefined;
var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */)
? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node))
@@ -93291,7 +94990,7 @@ var ts;
var nameToDeclarations = sourceFile.getNamedDeclarations();
var declarations = nameToDeclarations.get(name.text);
if (declarations) {
- var _loop_14 = function (declaration) {
+ var _loop_16 = function (declaration) {
var symbol = declaration.symbol;
if (symbol) {
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
@@ -93305,7 +95004,7 @@ var ts;
};
for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) {
var declaration = declarations_12[_b];
- var state_5 = _loop_14(declaration);
+ var state_5 = _loop_16(declaration);
if (typeof state_5 === "object")
return state_5.value;
}
@@ -93652,7 +95351,9 @@ var ts;
program.getSemanticDiagnostics(sourceFile);
var checker = program.getDiagnosticsProducingTypeChecker();
var diags = [];
- if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()))) {
+ if (sourceFile.commonJsModuleIndicator &&
+ (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) &&
+ containsTopLevelCommonjs(sourceFile)) {
diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module));
}
var isJsFile = ts.isSourceFileJavaScript(sourceFile);
@@ -93694,16 +95395,39 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
}
}
- return diags.concat(checker.getSuggestionDiagnostics(sourceFile));
+ return diags.concat(checker.getSuggestionDiagnostics(sourceFile)).sort(function (d1, d2) { return d1.start - d2.start; });
}
ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics;
+ // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
+ function containsTopLevelCommonjs(sourceFile) {
+ return sourceFile.statements.some(function (statement) {
+ switch (statement.kind) {
+ case 213 /* VariableStatement */:
+ return statement.declarationList.declarations.some(function (decl) {
+ return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true);
+ });
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ if (!ts.isBinaryExpression(expression))
+ return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true);
+ var kind = ts.getSpecialPropertyAssignmentKind(expression);
+ return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */;
+ }
+ default:
+ return false;
+ }
+ });
+ }
+ function propertyAccessLeftHandSide(node) {
+ return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node;
+ }
function importNameForConvertToDefaultImport(node) {
switch (node.kind) {
case 243 /* ImportDeclaration */:
@@ -94434,7 +96158,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_15 = function (opt) {
+ var _loop_17 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -94453,7 +96177,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_15(opt);
+ _loop_17(opt);
}
return options;
}
@@ -94857,6 +96581,7 @@ var ts;
rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
+ rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */),
// Special handling of unary operators.
// Prefix operators generally shouldn't have a space between
// them and their target unary expression.
@@ -95317,6 +97042,9 @@ var ts;
function isArrowFunctionContext(context) {
return context.contextNode.kind === 192 /* ArrowFunction */;
}
+ function isImportTypeContext(context) {
+ return context.contextNode.kind === 178 /* ImportType */;
+ }
function isNonJsxSameLineTokenContext(context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}
@@ -95439,18 +97167,18 @@ var ts;
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(map.length);
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
- var rule = rules_1[_i];
- var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
- for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
+ var rule_1 = rules_1[_i];
+ var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific;
+ for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) {
var left = _b[_a];
- for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) {
var right = _d[_c];
var index = getRuleBucketIndex(left, right);
var rulesBucket = map[index];
if (rulesBucket === undefined) {
rulesBucket = map[index] = [];
}
- addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
+ addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index);
}
}
}
@@ -96757,7 +98485,7 @@ var ts;
NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
})(NextTokenKind || (NextTokenKind = {}));
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
- var nextToken = ts.findNextToken(precedingToken, current);
+ var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
if (!nextToken) {
return 0 /* Unknown */;
}
@@ -96806,9 +98534,10 @@ var ts;
}
function getContainingList(node, sourceFile) {
if (node.parent) {
+ var end = node.end;
switch (node.parent.kind) {
case 161 /* TypeReference */:
- return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
case 183 /* ObjectLiteralExpression */:
return node.parent.properties;
case 182 /* ArrayLiteralExpression */:
@@ -96823,22 +98552,25 @@ var ts;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.parameters, start, end);
}
case 234 /* ClassDeclaration */:
- return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end);
case 187 /* NewExpression */:
case 186 /* CallExpression */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.arguments, start, end);
}
case 232 /* VariableDeclarationList */:
- return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
case 246 /* NamedImports */:
case 250 /* NamedExports */:
- return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
}
}
return undefined;
@@ -97160,10 +98892,10 @@ var ts;
return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getAdjustedEndPosition(sourceFile, node, options) {
+ var end = node.end;
if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
- return node.getEnd();
+ return end;
}
- var end = node.getEnd();
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
? newEnd
@@ -97188,7 +98920,8 @@ var ts;
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
this.changes = [];
- this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
+ 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
}
ChangeTracker.fromContext = function (context) {
@@ -97232,35 +98965,14 @@ var ts;
this.deleteNode(sourceFile, node);
return this;
}
- var id = ts.getNodeId(node);
- ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice");
- this.deletedNodesInLists[id] = true;
- if (index !== containingList.length - 1) {
- var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false);
- if (nextToken && isSeparator(node, nextToken)) {
- // find first non-whitespace position in the leading trivia of the node
- var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- var nextElement = containingList[index + 1];
- /// find first non-whitespace position in the leading trivia of the next node
- var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node
- this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
- }
- }
- else {
- var prev = containingList[index - 1];
- if (this.deletedNodesInLists[ts.getNodeId(prev)]) {
- var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
- var end = getAdjustedEndPosition(sourceFile, node, {});
- this.deleteRange(sourceFile, { pos: pos, end: end });
- }
- else {
- var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false);
- if (previousToken && isSeparator(node, previousToken)) {
- this.deleteNodeRange(sourceFile, previousToken, node);
- }
- }
- }
+ // 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) {
@@ -97289,10 +99001,13 @@ var ts;
if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
+ ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
+ var next = ts.findNextToken(node, node.parent, sourceFile);
+ return next && next.kind === 26 /* CommaToken */ ? next : undefined;
+ };
ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) {
- return this.replaceNode(sourceFile, oldNode, newNode, {
- suffix: "," + this.newLineCharacter
- });
+ var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
+ return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix });
};
ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
if (options === void 0) { options = {}; }
@@ -97326,7 +99041,8 @@ var ts;
// 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 text = "" + (insertAtLineStart ? "" : this.newLineCharacter) + sourceFile.text.slice(lineStartPosition, startPosition) + "//" + commentText + this.newLineCharacter;
+ var indent = sourceFile.text.slice(lineStartPosition, startPosition);
+ var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent;
this.insertText(sourceFile, token.getStart(sourceFile), text);
};
ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) {
@@ -97399,20 +99115,38 @@ var ts;
};
ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
var clsStart = cls.getStart(sourceFile);
- var prefix = "";
- var suffix = this.newLineCharacter;
- if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
- prefix = this.newLineCharacter;
- // For `class C {\n}`, don't add the trailing "\n"
- if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any'
- suffix = "";
- }
- }
var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
+ this.formatContext.options.indentSize;
- this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix });
+ this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls)));
+ };
+ ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) {
+ if (cls.members.length === 0) {
+ if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
+ // For `class C {\n}`, don't add the trailing "\n"
+ var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any'
+ return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" };
+ }
+ else {
+ return { prefix: "", suffix: this.newLineCharacter };
+ }
+ }
+ else {
+ return { prefix: this.newLineCharacter, suffix: "" };
+ }
+ };
+ ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
};
ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ 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));
+ };
+ ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
if (needSemicolonBetween(after, newNode)) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
@@ -97421,9 +99155,13 @@ var ts;
}
}
var endPosition = getAdjustedEndPosition(sourceFile, after, {});
- return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after));
+ return endPosition;
};
- ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) {
+ ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
+ var options = this.getInsertNodeAfterOptionsWorker(after);
+ 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 };
}
@@ -97468,13 +99206,16 @@ var ts;
this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
}
};
+ ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
+ this.insertText(sourceFile, node.getStart(sourceFile), "export ");
+ };
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
* i.e. arguments in arguments lists, parameters in parameter lists etc.
* Note that separators are part of the node in statements and class elements.
*/
- ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
- var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
+ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
+ if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
return this;
@@ -97592,6 +99333,19 @@ var ts;
}
});
};
+ ChangeTracker.prototype.finishTrailingCommaAfterDeletingNodesInList = function () {
+ var _this = this;
+ this.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);
+ if (lastNonDeletedIndex !== -1) {
+ _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) });
+ }
+ });
+ };
/**
* Note: after calling this, the TextChanges object must be discarded!
* @param validate only for tests
@@ -97600,11 +99354,24 @@ var ts;
*/
ChangeTracker.prototype.getChanges = function (validate) {
this.finishClassesWithNodesInsertedAtStart();
- return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ 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;
+ changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter));
+ }
+ return changes;
+ };
+ ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
+ this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
};
return ChangeTracker;
}());
textChanges_3.ChangeTracker = ChangeTracker;
+ // find first non-whitespace position in the leading trivia of the node
+ function startPositionToDeleteNodeInList(sourceFile, node) {
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ }
function getClassBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end];
}
@@ -97614,15 +99381,16 @@ var ts;
return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
var sourceFile = changesInFile[0].sourceFile;
// order changes by start position
- var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
- var _loop_16 = function (i) {
+ // 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_18 = 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_16(i);
+ _loop_18(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -97631,6 +99399,11 @@ var ts;
});
}
changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function newFileChanges(oldFile, fileName, statements, newLineCharacter) {
+ var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
+ return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true };
+ }
+ changesToText.newFileChanges = newFileChanges;
function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
if (change.kind === ChangeKind.Remove) {
return "";
@@ -97980,10 +99753,11 @@ var ts;
}
refactor_1.getEditsForRefactor = getEditsForRefactor;
})(refactor = ts.refactor || (ts.refactor = {}));
- function getRefactorContextLength(context) {
- return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition;
+ function getRefactorContextSpan(_a) {
+ var startPosition = _a.startPosition, endPosition = _a.endPosition;
+ return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
}
- ts.getRefactorContextLength = getRefactorContextLength;
+ ts.getRefactorContextSpan = getRefactorContextSpan;
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -98051,7 +99825,7 @@ var ts;
if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) {
if (!decl.typeParameters) {
var typeParameters = ts.getJSDocTypeParameterDeclarations(decl);
- if (typeParameters)
+ if (typeParameters.length)
changes.insertTypeParameters(sourceFile, decl, typeParameters);
}
var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile);
@@ -98087,18 +99861,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 161 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -98122,7 +99896,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
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);
@@ -98403,7 +100177,7 @@ var ts;
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
switch (importNode.kind) {
case 242 /* ImportEqualsDeclaration */:
- changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
+ changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
break;
case 186 /* CallExpression */:
if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
@@ -98467,7 +100241,7 @@ var ts;
case 186 /* CallExpression */: {
if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
// For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
+ changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
}
return false;
}
@@ -98540,27 +100314,30 @@ var ts;
changes.deleteNode(sourceFile, assignment.parent);
}
else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
+ : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
+ : undefined;
+ if (replacement) {
+ changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
+ return replacement[1];
+ }
+ else {
+ changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default");
+ return true;
}
- changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
- return changedToDefaultExport;
}
}
else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
convertNamedExport(sourceFile, assignment, changes, exports);
}
return false;
- var _a;
}
/**
* Convert `module.exports = { ... }` to individual exports..
* We can't always do this if the module has interesting members -- then it will be a default export instead.
*/
function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
+ var statements = ts.mapAllOrFail(object.properties, function (prop) {
switch (prop.kind) {
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
@@ -98576,6 +100353,7 @@ var ts;
ts.Debug.assertNever(prop);
}
});
+ return statements && [statements, false];
}
function convertNamedExport(sourceFile, assignment, changes, exports) {
// If "originalKeywordKind" was set, this is e.g. `exports.
@@ -98596,30 +100374,6 @@ var ts;
convertExportsPropertyAssignment(assignment, sourceFile, changes);
}
}
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 191 /* FunctionExpression */:
- case 192 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 204 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 186 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
function convertReExportAll(reExported, checker) {
// `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
var moduleSpecifier = reExported.text;
@@ -98695,7 +100449,7 @@ var ts;
: makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
});
if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
}
}
// falls through -- object destructuring has an interesting pattern and must be a variable declaration
@@ -98706,7 +100460,7 @@ var ts;
*/
var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
];
}
@@ -98755,7 +100509,7 @@ var ts;
// If it was unused, ensure that we at least import *something*.
needDefaultImport = true;
}
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
}
// Identifiers helpers
function makeUniqueName(name, identifiers) {
@@ -98797,17 +100551,9 @@ var ts;
}
function makeSingleImport(localName, propertyName, moduleSpecifier) {
return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
}
- function makeImport(name, namedImports, moduleSpecifier) {
- return makeImportDeclaration(name, namedImports, moduleSpecifier);
- }
- function makeImportDeclaration(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
- }
- codefix.makeImportDeclaration = makeImportDeclaration;
function makeImportSpecifier(propertyName, name) {
return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
}
@@ -98968,7 +100714,7 @@ var ts;
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, compilerOptions, getCanonicalFileName, host, preferences)).moduleSpecifier;
+ 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)) };
}
@@ -99014,11 +100760,11 @@ var ts;
if (context.symbolToken && ts.isIdentifier(context.symbolToken)) {
for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) {
var declaration = existingImports_1[_i].declaration;
- var namespace = getNamespaceImportName(declaration);
- if (namespace) {
- var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace));
+ var namespace_2 = getNamespaceImportName(declaration);
+ if (namespace_2) {
+ var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2));
if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) {
- useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken));
+ useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken));
}
}
}
@@ -99085,12 +100831,6 @@ var ts;
return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile);
}
}
- function usesJsExtensionOnImports(sourceFile) {
- return ts.firstDefined(sourceFile.imports, function (_a) {
- var text = _a.text;
- return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined;
- }) || false;
- }
function createImportClauseOfKind(kind, symbolName) {
var id = ts.createIdentifier(symbolName);
switch (kind) {
@@ -99104,274 +100844,15 @@ var ts;
ts.Debug.assertNever(kind);
}
}
- function getNewImportInfos(program, sourceFile, moduleSymbols, compilerOptions, getCanonicalFileName, host, preferences) {
- var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
- var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
- var addJsExtension = usesJsExtensionOnImports(sourceFile);
+ function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) {
var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) {
var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind;
- var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) {
- var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName);
- var global = tryGetModuleNameFromAmbientModule(moduleSymbol)
- || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension)
- || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory)
- || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName);
- if (global) {
- return [global];
- }
- var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension);
- if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
- return [relativePath];
- }
- var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
- if (!relativeToBaseUrl) {
- return [relativePath];
- }
- var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension);
- if (paths) {
- var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
- if (fromPaths) {
- return [fromPaths];
- }
- }
- if (preferences.importModuleSpecifierPreference === "non-relative") {
- return [importRelativeToBaseUrl];
- }
- if (preferences.importModuleSpecifierPreference !== undefined)
- ts.Debug.assertNever(preferences.importModuleSpecifierPreference);
- if (isPathRelativeToParent(relativeToBaseUrl)) {
- return [relativePath];
- }
- /*
- Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl.
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/a/b
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../../foo/bar
- getRelativePathNParents(relativePath) = 2
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 2 < 2 = false
- In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar".
-
- Suppose we have:
- baseUrl = /base
- sourceDirectory = /base/foo/a
- moduleFileName = /base/foo/bar
- Then:
- relativePath = ../a
- getRelativePathNParents(relativePath) = 1
- pathFromSourceToBaseUrl = ../../
- getRelativePathNParents(pathFromSourceToBaseUrl) = 2
- 1 < 2 = true
- In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
- */
- var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName);
- var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
- return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
- });
+ var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program, sourceFile, host, preferences);
return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ 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; }));
}
- /**
- * Looks for a existing imports that use symlinks to this module.
- * Only if no symlink is available, the real path will be used.
- */
- function getAllModulePaths(program, _a) {
- var fileName = _a.fileName;
- var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) {
- return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
- return res && res.resolvedFileName === fileName ? res.originalPath : undefined;
- });
- });
- return symlinks.length === 0 ? [fileName] : symlinks;
- }
- function getRelativePathNParents(relativePath) {
- var count = 0;
- for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) {
- count++;
- }
- return count;
- }
- function tryGetModuleNameFromAmbientModule(moduleSymbol) {
- var decl = moduleSymbol.valueDeclaration;
- if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) {
- return decl.name.text;
- }
- }
- function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
- for (var key in paths) {
- for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
- var patternText_1 = _a[_i];
- var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
- var indexOfStar = pattern.indexOf("*");
- if (indexOfStar === 0 && pattern.length === 1) {
- continue;
- }
- else if (indexOfStar !== -1) {
- var prefix = pattern.substr(0, indexOfStar);
- var suffix = pattern.substr(indexOfStar + 1);
- if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
- ts.startsWith(relativeToBaseUrl, prefix) &&
- ts.endsWith(relativeToBaseUrl, suffix)) {
- var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
- return key.replace("*", matchedStar);
- }
- }
- else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
- return key;
- }
- }
- }
- }
- function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
- var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
- if (normalizedTargetPath === undefined) {
- return undefined;
- }
- var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
- var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath;
- return ts.removeFileExtension(relativePath);
- }
- function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
- var roots = ts.getEffectiveTypeRoots(options, host);
- return ts.firstDefined(roots, function (unNormalizedTypeRoot) {
- var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName);
- if (ts.startsWith(moduleFileName, typeRoot)) {
- // For a type definition, we can strip `/index` even with classic resolution.
- return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension);
- }
- });
- }
- function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) {
- if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
- // nothing to do here
- return undefined;
- }
- var parts = getNodeModulePathParts(moduleFileName);
- if (!parts) {
- return undefined;
- }
- // Simplify the full file path to something that can be resolved by Node.
- // If the module could be imported by a directory name, use that directory's name
- var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
- // Get a path that's relative to node_modules or the importing file's path
- moduleSpecifier = getNodeResolvablePath(moduleSpecifier);
- // If the module was found in @types, get the actual Node package name
- return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier);
- function getDirectoryOrExtensionlessFileName(path) {
- // If the file is the main module, it can be imported by the package name
- var packageRootPath = path.substring(0, parts.packageRootIndex);
- var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
- if (host.fileExists(packageJsonPath)) {
- var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
- if (packageJsonContent) {
- var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
- if (mainFileRelative) {
- var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
- if (mainExportFile === getCanonicalFileName(path)) {
- return packageRootPath;
- }
- }
- }
- }
- // We still have a file name - remove the extension
- var fullModulePathWithoutExtension = ts.removeFileExtension(path);
- // If the file is /index, it can be imported by its directory name
- if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") {
- return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
- }
- return fullModulePathWithoutExtension;
- }
- function getNodeResolvablePath(path) {
- var basePath = path.substring(0, parts.topLevelNodeModulesIndex);
- if (sourceDirectory.indexOf(basePath) === 0) {
- // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
- return path.substring(parts.topLevelPackageNameIndex + 1);
- }
- else {
- return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName);
- }
- }
- }
- function getNodeModulePathParts(fullPath) {
- // If fullPath can't be valid module file within node_modules, returns undefined.
- // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
- // Returns indices: ^ ^ ^ ^
- var topLevelNodeModulesIndex = 0;
- var topLevelPackageNameIndex = 0;
- var packageRootIndex = 0;
- var fileNameIndex = 0;
- var States;
- (function (States) {
- States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
- States[States["NodeModules"] = 1] = "NodeModules";
- States[States["Scope"] = 2] = "Scope";
- States[States["PackageContent"] = 3] = "PackageContent";
- })(States || (States = {}));
- var partStart = 0;
- var partEnd = 0;
- var state = 0 /* BeforeNodeModules */;
- while (partEnd >= 0) {
- partStart = partEnd;
- partEnd = fullPath.indexOf("/", partStart + 1);
- switch (state) {
- case 0 /* BeforeNodeModules */:
- if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
- topLevelNodeModulesIndex = partStart;
- topLevelPackageNameIndex = partEnd;
- state = 1 /* NodeModules */;
- }
- break;
- case 1 /* NodeModules */:
- case 2 /* Scope */:
- if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
- state = 2 /* Scope */;
- }
- else {
- packageRootIndex = partEnd;
- state = 3 /* PackageContent */;
- }
- break;
- case 3 /* PackageContent */:
- if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
- state = 1 /* NodeModules */;
- }
- else {
- state = 3 /* PackageContent */;
- }
- break;
- }
- }
- fileNameIndex = partStart;
- return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
- }
- function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
- return ts.firstDefined(rootDirs, function (rootDir) {
- var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
- return isPathRelativeToParent(relativePath) ? undefined : relativePath;
- });
- }
- function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) {
- var noExtension = ts.removeFileExtension(fileName);
- return addJsExtension
- ? noExtension + ".js"
- : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs
- ? ts.removeSuffix(noExtension, "/index")
- : noExtension;
- }
- function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
- var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
- }
- function isPathRelativeToParent(path) {
- return ts.startsWith(path, "..");
- }
function getCodeActionsForAddImport(exportInfos, ctx, existingImports, useExisting, addNew) {
var fromExistingImport = ts.firstDefined(existingImports, function (_a) {
var declaration = _a.declaration, importKind = _a.importKind;
@@ -99390,7 +100871,7 @@ var ts;
var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier);
var newImportInfos = existingDeclaration
? [existingDeclaration]
- : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host, ctx.preferences);
+ : 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));
@@ -99848,7 +101329,24 @@ var ts;
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName,
/*questionToken*/ undefined, typeNode,
/*initializer*/ undefined);
- changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
+ if (lastProp) {
+ changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property);
+ }
+ else {
+ changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ }
+ }
+ // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
+ function getNodeToInsertPropertyAfter(cls) {
+ var res;
+ for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ if (!ts.isPropertyDeclaration(member))
+ break;
+ res = member;
+ }
+ return res;
}
function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) {
// Index signatures cannot have the static modifier.
@@ -100160,6 +101658,7 @@ var ts;
ts.Diagnostics._0_is_declared_but_never_used.code,
ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
+ ts.Diagnostics.All_destructured_elements_are_unused.code,
];
codefix.registerCodeFix({
errorCodes: errorCodes,
@@ -100170,9 +101669,13 @@ var ts;
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(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, context.span.start, /*deleted*/ undefined); });
+ if (delDestructure.length) {
+ return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, 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); });
+ var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token, /*deleted*/ undefined); });
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));
}
@@ -100183,36 +101686,69 @@ var ts;
return result;
},
fixIds: [fixIdPrefix, fixIdDelete],
- getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
- var sourceFile = context.sourceFile;
- var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file);
- switch (context.fixId) {
- case fixIdPrefix:
- if (ts.isIdentifier(token) && canPrefix(token)) {
- tryPrefixDeclaration(changes, diag.code, sourceFile, token);
- }
- break;
- case fixIdDelete:
- var importDecl = tryGetFullImport(diag.file, diag.start);
- if (importDecl) {
- changes.deleteNode(sourceFile, importDecl);
- }
- else {
- tryDeleteDeclaration(changes, sourceFile, token);
- }
- break;
- default:
- ts.Debug.fail(JSON.stringify(context.fixId));
- }
- }); },
+ 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 NodeSet();
+ return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ var sourceFile = context.sourceFile;
+ var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file);
+ 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(diag.file, diag.start);
+ if (importDecl) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (!tryDeleteFullDestructure(changes, sourceFile, diag.start, deleted)) {
+ tryDeleteDeclaration(changes, sourceFile, token, deleted);
+ }
+ }
+ break;
+ default:
+ ts.Debug.fail(JSON.stringify(context.fixId));
+ }
+ });
+ },
});
// Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing.
function tryGetFullImport(sourceFile, pos) {
var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined;
}
+ function tryDeleteFullDestructure(changes, sourceFile, pos, deletedAncestors) {
+ var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent))
+ return false;
+ var decl = startToken.parent.parent;
+ switch (decl.kind) {
+ case 231 /* VariableDeclaration */:
+ tryDeleteVariableDeclaration(changes, sourceFile, decl, deletedAncestors);
+ break;
+ case 148 /* Parameter */:
+ if (deletedAncestors)
+ deletedAncestors.add(decl);
+ changes.deleteNodeInList(sourceFile, decl);
+ break;
+ case 181 /* BindingElement */:
+ if (deletedAncestors)
+ deletedAncestors.add(decl);
+ changes.deleteNode(sourceFile, decl);
+ break;
+ default:
+ return ts.Debug.assertNever(decl);
+ }
+ return true;
+ }
function getToken(sourceFile, pos) {
- var token = ts.findPrecedingToken(pos, sourceFile);
+ 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;
}
@@ -100237,38 +101773,45 @@ var ts;
}
return false;
}
- function tryDeleteDeclaration(changes, sourceFile, token) {
+ function tryDeleteDeclaration(changes, sourceFile, token, deletedAncestors) {
switch (token.kind) {
case 71 /* Identifier */:
- tryDeleteIdentifier(changes, sourceFile, token);
+ tryDeleteIdentifier(changes, sourceFile, token, deletedAncestors);
break;
case 151 /* PropertyDeclaration */:
case 245 /* NamespaceImport */:
+ if (deletedAncestors)
+ deletedAncestors.add(token.parent);
changes.deleteNode(sourceFile, token.parent);
break;
default:
- tryDeleteDefault(changes, sourceFile, token);
+ tryDeleteDefault(changes, sourceFile, token, deletedAncestors);
}
}
- function tryDeleteDefault(changes, sourceFile, token) {
+ function tryDeleteDefault(changes, sourceFile, token, deletedAncestors) {
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);
}
}
- function tryDeleteIdentifier(changes, sourceFile, identifier) {
+ function tryDeleteIdentifier(changes, sourceFile, identifier, deletedAncestors) {
var parent = identifier.parent;
switch (parent.kind) {
case 231 /* VariableDeclaration */:
- tryDeleteVariableDeclaration(changes, sourceFile, parent);
+ tryDeleteVariableDeclaration(changes, sourceFile, parent, deletedAncestors);
break;
case 147 /* TypeParameter */:
- var typeParameters = parent.parent.typeParameters;
+ var typeParameters = ts.getEffectiveTypeParameterDeclarations(parent.parent);
if (typeParameters.length === 1) {
- var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false);
- var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false);
+ 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);
@@ -100299,6 +101842,20 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
+ case 181 /* BindingElement */: {
+ var pattern = parent.parent;
+ switch (pattern.kind) {
+ case 180 /* ArrayBindingPattern */:
+ changes.deleteNode(sourceFile, parent); // Don't delete ','
+ break;
+ case 179 /* ObjectBindingPattern */:
+ changes.deleteNodeInList(sourceFile, parent);
+ break;
+ default:
+ return ts.Debug.assertNever(pattern);
+ }
+ break;
+ }
// handle case where 'import a = A;'
case 242 /* ImportEqualsDeclaration */:
var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */);
@@ -100337,7 +101894,7 @@ var ts;
tryDeleteNamedImportBinding(changes, sourceFile, parent);
break;
default:
- tryDeleteDefault(changes, sourceFile, identifier);
+ tryDeleteDefault(changes, sourceFile, identifier, deletedAncestors);
break;
}
}
@@ -100360,15 +101917,19 @@ var ts;
}
}
// token.parent is a variableDeclaration
- function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) {
+ function tryDeleteVariableDeclaration(changes, sourceFile, varDecl, deletedAncestors) {
switch (varDecl.parent.parent.kind) {
case 219 /* 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;
@@ -100377,6 +101938,8 @@ var ts;
var forOfStatement = varDecl.parent.parent;
ts.Debug.assert(forOfStatement.initializer.kind === 232 /* VariableDeclarationList */);
var forOfInitializer = forOfStatement.initializer;
+ if (deletedAncestors)
+ deletedAncestors.add(forOfInitializer.declarations[0]);
changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral());
break;
case 220 /* ForInStatement */:
@@ -100385,13 +101948,131 @@ var ts;
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);
}
}
}
+ var NodeSet = /** @class */ (function () {
+ function NodeSet() {
+ this.map = ts.createMap();
+ }
+ NodeSet.prototype.add = function (node) {
+ this.map.set(String(ts.getNodeId(node)), node);
+ };
+ NodeSet.prototype.some = function (pred) {
+ return ts.forEachEntry(this.map, pred) || false;
+ };
+ return NodeSet;
+ }());
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "fixUnreachableCode";
+ var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)];
+ },
+ fixIds: [fixId],
+ 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 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 216 /* IfStatement */:
+ if (container.elseStatement) {
+ if (ts.isBlock(statement.parent)) {
+ changes.deleteNodeRange(sourceFile, ts.first(statement.parent.statements), ts.last(statement.parent.statements));
+ }
+ else {
+ changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray));
+ }
+ break;
+ }
+ // falls through
+ case 218 /* WhileStatement */:
+ case 219 /* ForStatement */:
+ changes.deleteNode(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);
+ }
+ }
+ }
+ function shouldRemove(s) {
+ // Don't remove statements that can validly be used before they appear.
+ return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) &&
+ // `var x;` may declare a variable used above
+ !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
+ }
+ function isPurelyTypeDeclaration(s) {
+ switch (s.kind) {
+ case 235 /* InterfaceDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ return true;
+ case 238 /* ModuleDeclaration */:
+ return ts.getModuleInstanceState(s) !== 1 /* Instantiated */;
+ case 237 /* EnumDeclaration */:
+ return ts.hasModifier(s, 2048 /* Const */);
+ }
+ }
+ function sliceAfter(arr, value) {
+ var index = arr.indexOf(value);
+ ts.Debug.assert(index !== -1);
+ return arr.slice(index);
+ }
+ // Calls 'cb' with the start and end of each range where 'pred' is true.
+ function split(arr, pred, cb) {
+ ts.getRangesWhere(arr, pred, function (start, afterEnd) { return cb(arr[start], arr[afterEnd - 1]); });
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ var fixId = "fixUnusedLabel";
+ var errorCodes = [ts.Diagnostics.Unused_label.code];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
+ },
+ fixIds: [fixId],
+ 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 labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
+ var pos = token.getStart(sourceFile);
+ var statementPos = labeledStatement.statement.getStart(sourceFile);
+ // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
+ var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
+ : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
+ changes.deleteRange(sourceFile, { pos: pos, end: end });
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
@@ -100413,7 +102094,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 === 278 /* JSDocNullableType */) {
+ if (typeNode.kind === 280 /* 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, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -100433,7 +102114,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -100811,16 +102492,16 @@ var ts;
}
var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
var declaration;
- var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); });
+ 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)];
},
fixIds: [fixId],
getAllCodeActions: function (context) {
var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken;
- var seenFunctions = ts.createMap();
+ 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, seenFunctions);
+ doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, markSeen);
});
},
});
@@ -100834,7 +102515,7 @@ var ts;
return ts.Diagnostics.Infer_type_of_0_from_usage;
}
}
- function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) {
+ function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) {
if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) {
return undefined;
}
@@ -100843,17 +102524,18 @@ var ts;
// Variable and Property declarations
case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code:
case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code:
- if (ts.isVariableDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
+ if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location
annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken);
return parent;
}
return undefined;
case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: {
var symbol = program.getTypeChecker().getSymbolAtLocation(token);
- if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration)) {
+ if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) {
annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken);
return symbol.valueDeclaration;
}
+ return undefined;
}
}
var containingFunction = ts.getContainingFunction(token);
@@ -100869,7 +102551,7 @@ var ts;
}
// falls through
case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code:
- if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) {
+ if (markSeen(containingFunction)) {
var param = ts.cast(parent, ts.isParameter);
annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken);
return param;
@@ -101061,6 +102743,16 @@ var ts;
case 185 /* ElementAccessExpression */:
inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext);
break;
+ case 231 /* 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.
+ addCandidateType(usageContext, checker.getTypeAtLocation(initializer));
+ }
+ break;
+ }
+ }
+ // falls through
default:
return inferTypeFromContextualType(node, checker, usageContext);
}
@@ -101232,7 +102924,7 @@ var ts;
return checker.getStringType();
}
else if (usageContext.candidateTypes) {
- return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */));
+ return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker);
@@ -101349,7 +103041,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -101506,6 +103198,290 @@ var ts;
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
+// Used by importFixes to synthesize import module specifiers.
+/* @internal */
+var ts;
+(function (ts) {
+ var moduleSpecifiers;
+ (function (moduleSpecifiers) {
+ // For each symlink/original for a module, returns a list of ways to import that file.
+ function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) {
+ var compilerOptions = program.getCompilerOptions();
+ var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
+ var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions);
+ var addJsExtension = usesJsExtensionOnImports(importingSourceFile);
+ var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
+ var sourceDirectory = ts.getDirectoryPath(importingSourceFile.fileName);
+ return getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) {
+ var global = tryGetModuleNameFromAmbientModule(moduleSymbol)
+ || tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension)
+ || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory)
+ || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName);
+ if (global) {
+ return [global];
+ }
+ var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension);
+ if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
+ return [relativePath];
+ }
+ var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
+ if (!relativeToBaseUrl) {
+ return [relativePath];
+ }
+ var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension);
+ if (paths) {
+ var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
+ if (fromPaths) {
+ return [fromPaths];
+ }
+ }
+ if (preferences.importModuleSpecifierPreference === "non-relative") {
+ return [importRelativeToBaseUrl];
+ }
+ if (preferences.importModuleSpecifierPreference !== undefined)
+ ts.Debug.assertNever(preferences.importModuleSpecifierPreference);
+ if (isPathRelativeToParent(relativeToBaseUrl)) {
+ return [relativePath];
+ }
+ /*
+ Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl.
+
+ Suppose we have:
+ baseUrl = /base
+ sourceDirectory = /base/a/b
+ moduleFileName = /base/foo/bar
+ Then:
+ relativePath = ../../foo/bar
+ getRelativePathNParents(relativePath) = 2
+ pathFromSourceToBaseUrl = ../../
+ getRelativePathNParents(pathFromSourceToBaseUrl) = 2
+ 2 < 2 = false
+ In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar".
+
+ Suppose we have:
+ baseUrl = /base
+ sourceDirectory = /base/foo/a
+ moduleFileName = /base/foo/bar
+ Then:
+ relativePath = ../a
+ getRelativePathNParents(relativePath) = 1
+ pathFromSourceToBaseUrl = ../../
+ getRelativePathNParents(pathFromSourceToBaseUrl) = 2
+ 1 < 2 = true
+ In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
+ */
+ var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName));
+ var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
+ return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
+ });
+ }
+ moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
+ function usesJsExtensionOnImports(_a) {
+ var imports = _a.imports;
+ return ts.firstDefined(imports, function (_a) {
+ var text = _a.text;
+ return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined;
+ }) || false;
+ }
+ /**
+ * Looks for a existing imports that use symlinks to this module.
+ * Only if no symlink is available, the real path will be used.
+ */
+ function getAllModulePaths(program, _a) {
+ var fileName = _a.fileName;
+ var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) {
+ return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) {
+ return res && res.resolvedFileName === fileName ? res.originalPath : undefined;
+ });
+ });
+ return symlinks.length === 0 ? [fileName] : symlinks;
+ }
+ function getRelativePathNParents(relativePath) {
+ var components = ts.getPathComponents(relativePath);
+ if (components[0] || components.length === 1)
+ return 0;
+ for (var i = 1; i < components.length; i++) {
+ if (components[i] !== "..")
+ return i - 1;
+ }
+ return components.length - 1;
+ }
+ function tryGetModuleNameFromAmbientModule(moduleSymbol) {
+ var decl = moduleSymbol.valueDeclaration;
+ if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) {
+ return decl.name.text;
+ }
+ }
+ function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
+ for (var key in paths) {
+ for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
+ var patternText_1 = _a[_i];
+ var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
+ var indexOfStar = pattern.indexOf("*");
+ if (indexOfStar === 0 && pattern.length === 1) {
+ continue;
+ }
+ else if (indexOfStar !== -1) {
+ var prefix = pattern.substr(0, indexOfStar);
+ var suffix = pattern.substr(indexOfStar + 1);
+ if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
+ ts.startsWith(relativeToBaseUrl, prefix) &&
+ ts.endsWith(relativeToBaseUrl, suffix)) {
+ var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
+ return key.replace("*", matchedStar);
+ }
+ }
+ else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
+ return key;
+ }
+ }
+ }
+ }
+ function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) {
+ var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
+ if (normalizedTargetPath === undefined) {
+ return undefined;
+ }
+ var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
+ var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
+ return ts.removeFileExtension(relativePath);
+ }
+ function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
+ var roots = ts.getEffectiveTypeRoots(options, host);
+ return ts.firstDefined(roots, function (unNormalizedTypeRoot) {
+ var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName);
+ if (ts.startsWith(moduleFileName, typeRoot)) {
+ // For a type definition, we can strip `/index` even with classic resolution.
+ return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension);
+ }
+ });
+ }
+ function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) {
+ if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
+ // nothing to do here
+ return undefined;
+ }
+ var parts = getNodeModulePathParts(moduleFileName);
+ if (!parts) {
+ return undefined;
+ }
+ // Simplify the full file path to something that can be resolved by Node.
+ // If the module could be imported by a directory name, use that directory's name
+ var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
+ // Get a path that's relative to node_modules or the importing file's path
+ moduleSpecifier = getNodeResolvablePath(moduleSpecifier);
+ // If the module was found in @types, get the actual Node package name
+ return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier);
+ function getDirectoryOrExtensionlessFileName(path) {
+ // If the file is the main module, it can be imported by the package name
+ var packageRootPath = path.substring(0, parts.packageRootIndex);
+ var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
+ if (host.fileExists(packageJsonPath)) {
+ var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
+ if (packageJsonContent) {
+ var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
+ if (mainFileRelative) {
+ var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
+ if (mainExportFile === getCanonicalFileName(path)) {
+ return packageRootPath;
+ }
+ }
+ }
+ }
+ // We still have a file name - remove the extension
+ var fullModulePathWithoutExtension = ts.removeFileExtension(path);
+ // If the file is /index, it can be imported by its directory name
+ if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") {
+ return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
+ }
+ return fullModulePathWithoutExtension;
+ }
+ function getNodeResolvablePath(path) {
+ var basePath = path.substring(0, parts.topLevelNodeModulesIndex);
+ if (sourceDirectory.indexOf(basePath) === 0) {
+ // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
+ return path.substring(parts.topLevelPackageNameIndex + 1);
+ }
+ else {
+ return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName));
+ }
+ }
+ }
+ function getNodeModulePathParts(fullPath) {
+ // If fullPath can't be valid module file within node_modules, returns undefined.
+ // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
+ // Returns indices: ^ ^ ^ ^
+ var topLevelNodeModulesIndex = 0;
+ var topLevelPackageNameIndex = 0;
+ var packageRootIndex = 0;
+ var fileNameIndex = 0;
+ var States;
+ (function (States) {
+ States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
+ States[States["NodeModules"] = 1] = "NodeModules";
+ States[States["Scope"] = 2] = "Scope";
+ States[States["PackageContent"] = 3] = "PackageContent";
+ })(States || (States = {}));
+ var partStart = 0;
+ var partEnd = 0;
+ var state = 0 /* BeforeNodeModules */;
+ while (partEnd >= 0) {
+ partStart = partEnd;
+ partEnd = fullPath.indexOf("/", partStart + 1);
+ switch (state) {
+ case 0 /* BeforeNodeModules */:
+ if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
+ topLevelNodeModulesIndex = partStart;
+ topLevelPackageNameIndex = partEnd;
+ state = 1 /* NodeModules */;
+ }
+ break;
+ case 1 /* NodeModules */:
+ case 2 /* Scope */:
+ if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
+ state = 2 /* Scope */;
+ }
+ else {
+ packageRootIndex = partEnd;
+ state = 3 /* PackageContent */;
+ }
+ break;
+ case 3 /* PackageContent */:
+ if (fullPath.indexOf("/node_modules/", partStart) === partStart) {
+ state = 1 /* NodeModules */;
+ }
+ else {
+ state = 3 /* PackageContent */;
+ }
+ break;
+ }
+ }
+ fileNameIndex = partStart;
+ return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
+ }
+ function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
+ return ts.firstDefined(rootDirs, function (rootDir) {
+ var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
+ return isPathRelativeToParent(relativePath) ? undefined : relativePath;
+ });
+ }
+ function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) {
+ var noExtension = ts.removeFileExtension(fileName);
+ return addJsExtension
+ ? noExtension + ".js"
+ : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs
+ ? ts.removeSuffix(noExtension, "/index")
+ : noExtension;
+ }
+ function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
+ return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
+ }
+ function isPathRelativeToParent(path) {
+ return ts.startsWith(path, "..");
+ }
+ })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
+})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
@@ -101575,7 +103551,40 @@ var ts;
}
}
function doChange(changes, sourceFile, info) {
- changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (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];
+ codefix.registerCodeFix({
+ errorCodes: errorCodes,
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile, span = context.span;
+ var importType = getImportTypeNode(sourceFile, span.start);
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); });
+ return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)];
+ },
+ fixIds: [fixId],
+ getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) {
+ return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start));
+ }); },
+ });
+ function getImportTypeNode(sourceFile, pos) {
+ var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ ts.Debug.assert(token.kind === 91 /* ImportKeyword */);
+ ts.Debug.assert(token.parent.kind === 178 /* ImportType */);
+ return token.parent;
+ }
+ function doChange(changes, sourceFile, importType) {
+ var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true);
+ changes.replaceNode(sourceFile, importType, newTypeNode);
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
@@ -101593,7 +103602,7 @@ var ts;
* Exported for tests.
*/
function getAvailableActions(context) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
return undefined;
@@ -101662,7 +103671,7 @@ var ts;
extractSymbol.getAvailableActions = getAvailableActions;
/* Exported for tests */
function getEditsForAction(context, actionName) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
if (parsedFunctionIndexMatch) {
@@ -102774,8 +104783,8 @@ var ts;
i_1++;
}
// Note that we add the current node's type parameters *after* updating the corresponding scope.
- if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) {
- for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) {
+ if (ts.isDeclarationWithTypeParameters(curr)) {
+ for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) {
var typeParameterDecl = _b[_a];
var typeParameter = checker.getTypeAtLocation(typeParameterDecl);
if (allTypeParameterUsages.has(typeParameter.id.toString())) {
@@ -102797,7 +104806,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_17 = function (i) {
+ var _loop_19 = 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
@@ -102837,21 +104846,11 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_17(i);
+ _loop_19(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
- function hasTypeParameters(node) {
- return ts.isDeclarationWithTypeParameters(node) &&
- node.typeParameters !== undefined &&
- node.typeParameters.length > 0;
- }
function isInGenericContext(node) {
- for (; node; node = node.parent) {
- if (hasTypeParameters(node)) {
- return true;
- }
- }
- return false;
+ return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; });
}
function recordTypeParameterUsages(type) {
// PERF: This is potentially very expensive. `type` could be a library type with
@@ -103116,8 +105115,8 @@ 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, startPosition = context.startPosition;
- if (!getConvertibleFieldAtPosition(file, startPosition))
+ var file = context.file;
+ if (!getConvertibleFieldAtPosition(context, file))
return undefined;
return [{
name: actionName,
@@ -103131,27 +105130,46 @@ var ts;
}];
}
function getEditsForAction(context, _actionName) {
- var file = context.file, startPosition = context.startPosition;
- var fieldInfo = getConvertibleFieldAtPosition(file, startPosition);
+ var file = context.file;
+ var fieldInfo = getConvertibleFieldAtPosition(context, file);
if (!fieldInfo)
return undefined;
var isJS = ts.isSourceFileJavaScript(file);
var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor;
+ ts.suppressLeadingAndTrailingTrivia(fieldName);
+ ts.suppressLeadingAndTrailingTrivia(declaration);
+ ts.suppressLeadingAndTrailingTrivia(container);
var isInClassLike = ts.isClassLike(container);
+ // avoid Readonly modifier because it will convert to get accessor
+ var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
var accessorModifiers = isInClassLike
- ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers
+ ? !modifierFlags || modifierFlags & 8 /* Private */
+ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */)
+ : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
: undefined;
var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined;
- updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container);
+ updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
- var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(getAccessor);
insertAccessor(changeTracker, file, getAccessor, declaration, container);
- insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ if (isReadonly) {
+ // readonly modifier only existed in classLikeDeclaration
+ var constructor = ts.getFirstConstructorWithBody(container);
+ if (constructor) {
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ }
+ }
+ else {
+ var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(setAccessor);
+ insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ }
var edits = changeTracker.getChanges();
var renameFilename = file.fileName;
- var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1;
- var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false);
+ var nameNeedRename = renameAccessor ? accessorName : fieldName;
+ var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1;
+ var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration));
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function isConvertableName(name) {
@@ -103171,24 +105189,32 @@ var ts;
var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined);
return modifiers && ts.createNodeArray(modifiers);
}
- function getConvertibleFieldAtPosition(file, startPosition) {
+ 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);
var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
- // make sure propertyDeclaration have AccessibilityModifier or Static Modifier
- var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */;
- if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
+ // 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)
+ || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
return undefined;
- var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name);
- var accessorName = createPropertyName(declaration.name.text, declaration.name);
- ts.suppressLeadingAndTrailingTrivia(fieldName);
- ts.suppressLeadingAndTrailingTrivia(declaration);
+ var name = declaration.name.text;
+ var startWithUnderscore = startsWithUnderscore(name);
+ var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file.text), declaration.name);
+ var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file.text) : name, declaration.name);
return {
isStatic: ts.hasStaticModifier(declaration),
+ isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent,
+ originalName: declaration.name,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
+ renameAccessor: startWithUnderscore
};
}
function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) {
@@ -103212,16 +105238,11 @@ var ts;
var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
changeTracker.replaceNode(file, declaration, property);
}
- function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) {
- var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer);
- changeTracker.insertNodeAtClassStart(file, classLikeContainer, property);
- changeTracker.deleteNodeInList(file, declaration);
- }
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
- function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) {
+ function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
if (ts.isPropertyDeclaration(declaration)) {
updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
}
@@ -103229,19 +105250,636 @@ var ts;
updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
}
else {
- updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container);
+ changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
}
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
ts.isParameterPropertyDeclaration(declaration)
? changeTracker.insertNodeAtClassStart(file, container, accessor)
- : changeTracker.insertNodeAfter(file, declaration, accessor);
+ : ts.isPropertyAssignment(declaration)
+ ? changeTracker.insertNodeAfterComma(file, declaration, accessor)
+ : changeTracker.insertNodeAfter(file, declaration, accessor);
+ }
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ if (!constructor.body)
+ return;
+ var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
+ var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); });
+ ts.forEach(referenceEntries, function (entry) {
+ var parent = entry.parent;
+ var accessorName = ts.createIdentifier(fieldName.text);
+ var node = ts.isBinaryExpression(parent)
+ ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
+ : ts.isPropertyAccessExpression(parent)
+ ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
+ : ts.Debug.fail("Unexpected write access token");
+ changeTracker.replaceNode(file, parent, node);
+ });
}
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var refactorName = "Move to a new file";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ if (!context.preferences.allowTextChangesInNewFiles || getFirstAndLastStatementToMove(context) === undefined)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
+ return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var statements = ts.Debug.assertDefined(getStatementsToMove(context));
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ });
+ function getFirstAndLastStatementToMove(context) {
+ var file = context.file;
+ var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
+ var statements = file.statements;
+ var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
+ if (startNodeIndex === -1)
+ return undefined;
+ // Can't only partially include the start node or be partially into the next node
+ if (range.pos > statements[startNodeIndex].getStart(file))
+ return undefined;
+ var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
+ // Can't be partially into the next node
+ if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
+ return undefined;
+ return { first: startNodeIndex, afterLast: afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex };
+ }
+ function doChange(oldFile, program, toMove, changes, host) {
+ var checker = program.getTypeChecker();
+ var usage = getUsageInfo(oldFile, toMove.all, checker);
+ var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
+ var extension = ts.extensionFromPath(oldFile.fileName);
+ var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
+ var newFileNameWithExtension = newModuleName + extension;
+ // If previous file was global, this is easy.
+ changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName));
+ addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
+ }
+ // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file.
+ function getStatementsToMove(context) {
+ var statements = context.file.statements;
+ var _a = getFirstAndLastStatementToMove(context), first = _a.first, afterLast = _a.afterLast;
+ var all = [];
+ var ranges = [];
+ var rangeToMove = statements.slice(first, afterLast);
+ ts.getRangesWhere(rangeToMove, function (s) { return !isPureImport(s); }, function (start, afterEnd) {
+ for (var i = start; i < afterEnd; i++)
+ all.push(rangeToMove[i]);
+ ranges.push({ first: rangeToMove[start], last: rangeToMove[afterEnd - 1] });
+ });
+ return { all: all, ranges: ranges };
+ }
+ function isPureImport(node) {
+ switch (node.kind) {
+ case 243 /* ImportDeclaration */:
+ return true;
+ case 242 /* ImportEqualsDeclaration */:
+ return !ts.hasModifier(node, 1 /* Export */);
+ case 213 /* VariableStatement */:
+ return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
+ default:
+ return false;
+ }
+ }
+ function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
+ var cfg = program.getCompilerOptions().configFile;
+ if (!cfg)
+ return;
+ var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
+ var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
+ var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
+ var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
+ return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
+ });
+ if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
+ changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
+ }
+ }
+ function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) {
+ var checker = program.getTypeChecker();
+ if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
+ deleteMovedStatements(oldFile, toMove.ranges, changes);
+ return toMove.all;
+ }
+ var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
+ var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax);
+ if (importsFromNewFile) {
+ changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true);
+ }
+ deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker);
+ deleteMovedStatements(oldFile, toMove.ranges, changes);
+ updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
+ return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
+ }
+ function deleteMovedStatements(sourceFile, moved, changes) {
+ for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) {
+ var _a = moved_1[_i], first_1 = _a.first, last_3 = _a.last;
+ changes.deleteNodeRange(sourceFile, first_1, last_3);
+ }
+ }
+ function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
+ }
+ }
+ function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
+ var checker = program.getTypeChecker();
+ var _loop_20 = function (sourceFile) {
+ if (sourceFile === oldFile)
+ return "continue";
+ var _loop_21 = function (statement) {
+ forEachImportInStatement(statement, function (importNode) {
+ var shouldMove = function (name) {
+ var symbol = ts.isBindingElement(name.parent)
+ ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
+ : ts.skipAlias(checker.getSymbolAtLocation(name), checker);
+ return !!symbol && movedSymbols.has(symbol);
+ };
+ deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
+ var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
+ var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
+ if (newImportDeclaration)
+ changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
+ });
+ };
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ _loop_21(statement);
+ }
+ };
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ _loop_20(sourceFile);
+ }
+ }
+ function moduleSpecifierFromImport(i) {
+ return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier
+ : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
+ : i.initializer.arguments[0]);
+ }
+ function forEachImportInStatement(statement, cb) {
+ if (ts.isImportDeclaration(statement)) {
+ if (ts.isStringLiteral(statement.moduleSpecifier))
+ cb(statement);
+ }
+ else if (ts.isImportEqualsDeclaration(statement)) {
+ if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
+ cb(statement);
+ }
+ }
+ else if (ts.isVariableStatement(statement)) {
+ for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
+ cb(decl);
+ }
+ }
+ }
+ }
+ function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) {
+ var defaultImport;
+ var imports = [];
+ newFileNeedExport.forEach(function (symbol) {
+ if (symbol.escapedName === "default" /* Default */) {
+ defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol));
+ }
+ else {
+ imports.push(symbol.name);
+ }
+ });
+ return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports);
+ }
+ function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) {
+ path = ts.ensurePathIsNonModuleName(path);
+ if (useEs6Imports) {
+ var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
+ return ts.makeImportIfNecessary(defaultImport, specifiers, path);
+ }
+ else {
+ ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module.
+ var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
+ return bindingElements.length
+ ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
+ : undefined;
+ }
+ }
+ function makeVariableStatement(name, type, initializer, flags) {
+ if (flags === void 0) { flags = 2 /* Const */; }
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
+ }
+ function createRequireCall(moduleSpecifier) {
+ return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
+ }
+ function addExports(sourceFile, toMove, needExport, useEs6Exports) {
+ return ts.flatMap(toMove, function (statement) {
+ if (isTopLevelDeclarationStatement(statement) &&
+ !isExported(sourceFile, statement, useEs6Exports) &&
+ forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
+ var exports_2 = addExport(statement, useEs6Exports);
+ if (exports_2)
+ return exports_2;
+ }
+ return statement;
+ });
+ }
+ function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
+ switch (importDecl.kind) {
+ case 243 /* ImportDeclaration */:
+ deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ case 242 /* ImportEqualsDeclaration */:
+ if (isUnused(importDecl.name)) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ break;
+ case 231 /* VariableDeclaration */:
+ deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ default:
+ ts.Debug.assertNever(importDecl);
+ }
+ }
+ function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
+ if (!importDecl.importClause)
+ return;
+ var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ var defaultUnused = !name || isUnused(name);
+ var namedBindingsUnused = !namedBindings ||
+ (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
+ if (defaultUnused && namedBindingsUnused) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (name && defaultUnused) {
+ changes.deleteNode(sourceFile, name);
+ }
+ if (namedBindings) {
+ if (namedBindingsUnused) {
+ changes.deleteNode(sourceFile, namedBindings);
+ }
+ else if (namedBindings.kind === 246 /* NamedImports */) {
+ for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
+ var element = _b[_i];
+ if (isUnused(element.name))
+ changes.deleteNodeInList(sourceFile, element);
+ }
+ }
+ }
+ }
+ }
+ function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
+ var name = varDecl.name;
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ if (isUnused(name)) {
+ changes.deleteNode(sourceFile, name);
+ }
+ break;
+ case 180 /* ArrayBindingPattern */:
+ break;
+ case 179 /* 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);
+ }
+ 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);
+ }
+ }
+ }
+ break;
+ }
+ }
+ function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) {
+ var copiedOldImports = [];
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var oldStatement = _a[_i];
+ forEachImportInStatement(oldStatement, function (i) {
+ ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
+ });
+ }
+ // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
+ var oldFileDefault;
+ var oldFileNamedImports = [];
+ var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
+ newFileImportsFromOldFile.forEach(function (symbol) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (!isTopLevelDeclaration(decl))
+ continue;
+ var name = nameOfTopLevelDeclaration(decl);
+ if (!name)
+ continue;
+ var top = getTopLevelDeclarationStatement(decl);
+ if (markSeenTop(top)) {
+ addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
+ }
+ if (ts.hasModifier(decl, 512 /* Default */)) {
+ oldFileDefault = name;
+ }
+ else {
+ oldFileNamedImports.push(name.text);
+ }
+ }
+ });
+ ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax));
+ return copiedOldImports;
+ }
+ function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
+ var newModuleName = moduleName;
+ for (var i = 1;; i++) {
+ var name = ts.combinePaths(inDirectory, newModuleName + extension);
+ if (!host.fileExists(name))
+ return newModuleName;
+ newModuleName = moduleName + "." + i;
+ }
+ }
+ function getNewModuleName(movedSymbols) {
+ return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
+ }
+ function getUsageInfo(oldFile, toMove, checker) {
+ var movedSymbols = new SymbolSet();
+ var oldImportsNeededByNewFile = new SymbolSet();
+ var newFileImportsFromOldFile = new SymbolSet();
+ for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
+ var statement = toMove_1[_i];
+ forEachTopLevelDeclaration(statement, function (decl) {
+ movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
+ });
+ }
+ for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
+ var statement = toMove_2[_a];
+ forEachReference(statement, checker, function (symbol) {
+ if (!symbol.declarations)
+ return;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (isInImport(decl)) {
+ oldImportsNeededByNewFile.add(symbol);
+ }
+ else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) {
+ newFileImportsFromOldFile.add(symbol);
+ }
+ }
+ });
+ }
+ var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
+ var oldFileImportsFromNewFile = new SymbolSet();
+ for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
+ var statement = _c[_b];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachReference(statement, checker, function (symbol) {
+ if (movedSymbols.has(symbol))
+ oldFileImportsFromNewFile.add(symbol);
+ unusedImportsFromOldFile.delete(symbol);
+ });
+ }
+ return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
+ }
+ // Below should all be utilities
+ function isInImport(decl) {
+ switch (decl.kind) {
+ case 242 /* ImportEqualsDeclaration */:
+ case 247 /* ImportSpecifier */:
+ case 244 /* ImportClause */:
+ return true;
+ case 231 /* VariableDeclaration */:
+ return isVariableDeclarationInImport(decl);
+ case 181 /* BindingElement */:
+ return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
+ default:
+ return false;
+ }
+ }
+ function isVariableDeclarationInImport(decl) {
+ return ts.isSourceFile(decl.parent.parent.parent) &&
+ decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
+ }
+ function filterImport(i, moduleSpecifier, keep) {
+ switch (i.kind) {
+ case 243 /* ImportDeclaration */: {
+ var clause = i.importClause;
+ if (!clause)
+ return undefined;
+ var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
+ var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
+ return defaultImport || namedBindings
+ ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
+ : undefined;
+ }
+ case 242 /* ImportEqualsDeclaration */:
+ return keep(i.name) ? i : undefined;
+ case 231 /* VariableDeclaration */: {
+ var name = filterBindingName(i.name, keep);
+ return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
+ }
+ default:
+ return ts.Debug.assertNever(i);
+ }
+ }
+ function filterNamedBindings(namedBindings, keep) {
+ if (namedBindings.kind === 245 /* NamespaceImport */) {
+ return keep(namedBindings.name) ? namedBindings : undefined;
+ }
+ else {
+ var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
+ return newElements.length ? ts.createNamedImports(newElements) : undefined;
+ }
+ }
+ function filterBindingName(name, keep) {
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ return keep(name) ? name : undefined;
+ case 180 /* ArrayBindingPattern */:
+ return name;
+ case 179 /* 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;
+ }
+ }
+ }
+ function forEachReference(node, checker, onReference) {
+ node.forEachChild(function cb(node) {
+ if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
+ var sym = checker.getSymbolAtLocation(node);
+ if (sym)
+ onReference(sym);
+ }
+ else {
+ node.forEachChild(cb);
+ }
+ });
+ }
+ var SymbolSet = /** @class */ (function () {
+ function SymbolSet() {
+ this.map = ts.createMap();
+ }
+ SymbolSet.prototype.add = function (symbol) {
+ this.map.set(String(ts.getSymbolId(symbol)), symbol);
+ };
+ SymbolSet.prototype.has = function (symbol) {
+ return this.map.has(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.delete = function (symbol) {
+ this.map.delete(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ SymbolSet.prototype.forEachEntry = function (cb) {
+ return ts.forEachEntry(this.map, cb);
+ };
+ SymbolSet.prototype.clone = function () {
+ var clone = new SymbolSet();
+ ts.copyEntries(this.map, clone.map);
+ return clone;
+ };
+ return SymbolSet;
+ }());
+ function isTopLevelDeclaration(node) {
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
+ }
+ function isTopLevelDeclarationStatement(node) {
+ ts.Debug.assert(ts.isSourceFile(node.parent));
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
+ }
+ function isNonVariableTopLevelDeclaration(node) {
+ switch (node.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function forEachTopLevelDeclaration(statement, cb) {
+ switch (statement.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return cb(statement);
+ case 213 /* VariableStatement */:
+ return ts.forEach(statement.declarationList.declarations, cb);
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */
+ ? cb(statement)
+ : undefined;
+ }
+ }
+ }
+ function nameOfTopLevelDeclaration(d) {
+ return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
+ }
+ function getTopLevelDeclarationStatement(d) {
+ return ts.isVariableDeclaration(d) ? d.parent.parent : d;
+ }
+ function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
+ if (isExported(sourceFile, decl, useEs6Exports))
+ return;
+ if (useEs6Exports) {
+ if (!ts.isExpressionStatement(decl))
+ changes.insertExportModifier(sourceFile, decl);
+ }
+ else {
+ var names = getNamesToExportInCommonJS(decl);
+ if (names.length !== 0)
+ changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
+ }
+ }
+ function isExported(sourceFile, decl, useEs6Exports) {
+ if (useEs6Exports) {
+ return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
+ }
+ else {
+ return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
+ }
+ }
+ function addExport(decl, useEs6Exports) {
+ return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
+ }
+ function addEs6Export(d) {
+ var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
+ switch (d.kind) {
+ case 233 /* FunctionDeclaration */:
+ return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
+ case 234 /* ClassDeclaration */:
+ return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 213 /* VariableStatement */:
+ return ts.updateVariableStatement(d, modifiers, d.declarationList);
+ case 238 /* ModuleDeclaration */:
+ return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
+ case 237 /* EnumDeclaration */:
+ return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
+ case 236 /* TypeAliasDeclaration */:
+ return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
+ case 235 /* InterfaceDeclaration */:
+ return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 242 /* ImportEqualsDeclaration */:
+ return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ return ts.Debug.assertNever(d);
+ }
+ }
+ function addCommonjsExport(decl) {
+ return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment));
+ }
+ function getNamesToExportInCommonJS(decl) {
+ switch (decl.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ return [decl.name.text];
+ case 213 /* VariableStatement */:
+ return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return undefined;
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ ts.Debug.assertNever(decl);
+ }
+ }
+ /** Creates `exports.x = x;` */
+ function createExportAssignment(name) {
+ return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name)));
+ }
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var sourcemaps;
(function (sourcemaps) {
@@ -103563,7 +106201,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 297 /* LastJSDocNode */; });
return child.kind < 145 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -103633,7 +106271,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(298 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
@@ -104156,6 +106794,9 @@ var ts;
HostCache.prototype.compilationSettings = function () {
return this._compilationSettings;
};
+ HostCache.prototype.getProjectReferences = function () {
+ return this.host.getProjectReferences && this.host.getProjectReferences();
+ };
HostCache.prototype.createEntry = function (fileName, path) {
var entry;
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
@@ -104185,9 +106826,18 @@ var ts;
return ts.isString(info) ? undefined : info;
};
HostCache.prototype.getRootFileNames = function () {
- return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) {
- return ts.isString(entry) ? entry : entry.hostFileName;
+ var names = [];
+ this.fileNameToEntry.forEach(function (entry) {
+ if (ts.isString(entry)) {
+ names.push(entry);
+ }
+ else {
+ if (entry.scriptKind !== 6 /* JSON */) {
+ names.push(entry.hostFileName);
+ }
+ }
});
+ return names;
};
HostCache.prototype.getVersion = function (path) {
var file = this.getHostFileInformation(path);
@@ -104363,6 +107013,7 @@ var ts;
}
ts.createSourceFileLikeCache = createSourceFileLikeCache;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
var syntaxTreeCache = new SyntaxTreeCache(host);
@@ -104466,7 +107117,14 @@ var ts;
};
}
var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
- program = ts.createProgram(rootFileNames, newSettings, compilerHost, program);
+ var options = {
+ rootNames: rootFileNames,
+ options: newSettings,
+ host: compilerHost,
+ oldProgram: program,
+ projectReferences: hostCache.getProjectReferences()
+ };
+ program = ts.createProgram(options);
// hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
// It needs to be cleared to allow all collected snapshots to be released
hostCache = undefined;
@@ -104670,6 +107328,11 @@ var ts;
}
return checker.getSymbolAtLocation(node);
}
+ function toLineColumnOffset(fileName, position) {
+ var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
+ var file = program.getSourceFile(path) || sourcemappedFileCache.get(path);
+ 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 base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
@@ -104741,27 +107404,28 @@ var ts;
}
function makeGetTargetOfMappedPosition(extract, create) {
return getTargetOfMappedPosition;
- function getTargetOfMappedPosition(input) {
+ function getTargetOfMappedPosition(input, original) {
+ if (original === void 0) { original = input; }
var info = extract(input);
if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) {
- var file = program.getSourceFile(info.fileName);
- if (!file) {
+ var file_18 = program.getSourceFile(info.fileName);
+ if (!file_18) {
var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName);
- file = sourcemappedFileCache.get(path);
+ file_18 = sourcemappedFileCache.get(path);
}
- if (!file) {
+ if (!file_18) {
return input;
}
- var mapper = getSourceMapper(info.fileName, file);
+ var mapper = getSourceMapper(info.fileName, file_18);
var newLoc = mapper.getOriginalPosition(info);
if (newLoc === info)
return input;
- return getTargetOfMappedPosition(create(newLoc, input));
+ return getTargetOfMappedPosition(create(newLoc, input, original), original);
}
return input;
}
}
- var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info) { return ({
+ var getTargetOfMappedDeclarationInfo = makeGetTargetOfMappedPosition(function (info) { return ({ fileName: info.fileName, position: info.textSpan.start }); }, function (newLoc, info, original) { return ({
containerKind: info.containerKind,
containerName: info.containerName,
fileName: newLoc.fileName,
@@ -104770,10 +107434,12 @@ var ts;
textSpan: {
start: newLoc.position,
length: info.textSpan.length
- }
+ },
+ originalFileName: original.fileName,
+ originalTextSpan: original.textSpan
}); });
function getTargetOfMappedDeclarationFiles(infos) {
- return ts.map(infos, getTargetOfMappedDeclarationInfo);
+ return ts.map(infos, function (d) { return getTargetOfMappedDeclarationInfo(d); });
}
/// Goto definition
function getDefinitionAtPosition(fileName, position) {
@@ -104806,10 +107472,12 @@ var ts;
textSpan: {
start: newLoc.position,
length: info.textSpan.length
- }
+ },
+ originalFileName: info.fileName,
+ originalTextSpan: info.textSpan
}); });
function getTargetOfMappedImplementationLocations(infos) {
- return ts.map(infos, getTargetOfMappedImplementationLocation);
+ return ts.map(infos, function (d) { return getTargetOfMappedImplementationLocation(d); });
}
function getImplementationAtPosition(fileName, position) {
synchronizeHostData();
@@ -105317,8 +107985,8 @@ var ts;
getProgram: getProgram,
getApplicableRefactors: getApplicableRefactors,
getEditsForRefactor: getEditsForRefactor,
+ toLineColumnOffset: toLineColumnOffset
};
- var _a;
}
ts.createLanguageService = createLanguageService;
/* @internal */
@@ -105389,20 +108057,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_6 = [];
+ var result_7 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_6.push(symbol);
+ result_7.push(symbol);
}
});
- return result_6;
+ return result_7;
}
if (symbol) {
- result_6.push(symbol);
- return result_6;
+ result_7.push(symbol);
+ return result_7;
}
}
return undefined;
@@ -105469,7 +108137,7 @@ var ts;
return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
- return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
+ return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
@@ -105484,7 +108152,7 @@ var ts;
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
- return spanInNode(ts.findNextToken(node, node.parent));
+ return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
}
function spanInNode(node) {
if (node) {
@@ -106823,5 +109491,3 @@ var TypeScript;
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-
-//# sourceMappingURL=typescriptServices.js.map
diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js
index a273ff745f7..ab3cb0310f4 100644
--- a/lib/typingsInstaller.js
+++ b/lib/typingsInstaller.js
@@ -34,564 +34,18 @@ var __extends = (this && this.__extends) || (function () {
})();
var ts;
(function (ts) {
- var Comparison;
- (function (Comparison) {
- Comparison[Comparison["LessThan"] = -1] = "LessThan";
- Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
- Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
- })(Comparison = ts.Comparison || (ts.Comparison = {}));
- var SyntaxKind;
- (function (SyntaxKind) {
- SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
- SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
- SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
- SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
- SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
- SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
- SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
- SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
- SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
- SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral";
- SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText";
- SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces";
- SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral";
- SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral";
- SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead";
- SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle";
- SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail";
- SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken";
- SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken";
- SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken";
- SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken";
- SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken";
- SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken";
- SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken";
- SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken";
- SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken";
- SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken";
- SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken";
- SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken";
- SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken";
- SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken";
- SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken";
- SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken";
- SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken";
- SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken";
- SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken";
- SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken";
- SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken";
- SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken";
- SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken";
- SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken";
- SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken";
- SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken";
- SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken";
- SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken";
- SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken";
- SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken";
- SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken";
- SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken";
- SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken";
- SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken";
- SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken";
- SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken";
- SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken";
- SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken";
- SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken";
- SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken";
- SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken";
- SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken";
- SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken";
- SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken";
- SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken";
- SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken";
- SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken";
- SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier";
- SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword";
- SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword";
- SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword";
- SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword";
- SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword";
- SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword";
- SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword";
- SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword";
- SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword";
- SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword";
- SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword";
- SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword";
- SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword";
- SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword";
- SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword";
- SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword";
- SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword";
- SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword";
- SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword";
- SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword";
- SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword";
- SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword";
- SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword";
- SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword";
- SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword";
- SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword";
- SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword";
- SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword";
- SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword";
- SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword";
- SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword";
- SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword";
- SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword";
- SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword";
- SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword";
- SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword";
- SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword";
- SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword";
- SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword";
- SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword";
- SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword";
- SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword";
- SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword";
- SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword";
- SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword";
- SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword";
- SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword";
- SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword";
- SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword";
- SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword";
- SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword";
- SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword";
- SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword";
- SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword";
- SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword";
- SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword";
- SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword";
- SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword";
- SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword";
- SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword";
- SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword";
- SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword";
- SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword";
- SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword";
- SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword";
- SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword";
- SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword";
- SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword";
- SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword";
- SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword";
- SyntaxKind[SyntaxKind["FromKeyword"] = 142] = "FromKeyword";
- SyntaxKind[SyntaxKind["GlobalKeyword"] = 143] = "GlobalKeyword";
- SyntaxKind[SyntaxKind["OfKeyword"] = 144] = "OfKeyword";
- SyntaxKind[SyntaxKind["QualifiedName"] = 145] = "QualifiedName";
- SyntaxKind[SyntaxKind["ComputedPropertyName"] = 146] = "ComputedPropertyName";
- SyntaxKind[SyntaxKind["TypeParameter"] = 147] = "TypeParameter";
- SyntaxKind[SyntaxKind["Parameter"] = 148] = "Parameter";
- SyntaxKind[SyntaxKind["Decorator"] = 149] = "Decorator";
- SyntaxKind[SyntaxKind["PropertySignature"] = 150] = "PropertySignature";
- SyntaxKind[SyntaxKind["PropertyDeclaration"] = 151] = "PropertyDeclaration";
- SyntaxKind[SyntaxKind["MethodSignature"] = 152] = "MethodSignature";
- SyntaxKind[SyntaxKind["MethodDeclaration"] = 153] = "MethodDeclaration";
- SyntaxKind[SyntaxKind["Constructor"] = 154] = "Constructor";
- SyntaxKind[SyntaxKind["GetAccessor"] = 155] = "GetAccessor";
- SyntaxKind[SyntaxKind["SetAccessor"] = 156] = "SetAccessor";
- SyntaxKind[SyntaxKind["CallSignature"] = 157] = "CallSignature";
- SyntaxKind[SyntaxKind["ConstructSignature"] = 158] = "ConstructSignature";
- SyntaxKind[SyntaxKind["IndexSignature"] = 159] = "IndexSignature";
- SyntaxKind[SyntaxKind["TypePredicate"] = 160] = "TypePredicate";
- SyntaxKind[SyntaxKind["TypeReference"] = 161] = "TypeReference";
- SyntaxKind[SyntaxKind["FunctionType"] = 162] = "FunctionType";
- SyntaxKind[SyntaxKind["ConstructorType"] = 163] = "ConstructorType";
- SyntaxKind[SyntaxKind["TypeQuery"] = 164] = "TypeQuery";
- SyntaxKind[SyntaxKind["TypeLiteral"] = 165] = "TypeLiteral";
- SyntaxKind[SyntaxKind["ArrayType"] = 166] = "ArrayType";
- SyntaxKind[SyntaxKind["TupleType"] = 167] = "TupleType";
- SyntaxKind[SyntaxKind["UnionType"] = 168] = "UnionType";
- SyntaxKind[SyntaxKind["IntersectionType"] = 169] = "IntersectionType";
- SyntaxKind[SyntaxKind["ConditionalType"] = 170] = "ConditionalType";
- SyntaxKind[SyntaxKind["InferType"] = 171] = "InferType";
- SyntaxKind[SyntaxKind["ParenthesizedType"] = 172] = "ParenthesizedType";
- SyntaxKind[SyntaxKind["ThisType"] = 173] = "ThisType";
- SyntaxKind[SyntaxKind["TypeOperator"] = 174] = "TypeOperator";
- SyntaxKind[SyntaxKind["IndexedAccessType"] = 175] = "IndexedAccessType";
- SyntaxKind[SyntaxKind["MappedType"] = 176] = "MappedType";
- SyntaxKind[SyntaxKind["LiteralType"] = 177] = "LiteralType";
- SyntaxKind[SyntaxKind["ImportType"] = 178] = "ImportType";
- SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 179] = "ObjectBindingPattern";
- SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 180] = "ArrayBindingPattern";
- SyntaxKind[SyntaxKind["BindingElement"] = 181] = "BindingElement";
- SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 182] = "ArrayLiteralExpression";
- SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 183] = "ObjectLiteralExpression";
- SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 184] = "PropertyAccessExpression";
- SyntaxKind[SyntaxKind["ElementAccessExpression"] = 185] = "ElementAccessExpression";
- SyntaxKind[SyntaxKind["CallExpression"] = 186] = "CallExpression";
- SyntaxKind[SyntaxKind["NewExpression"] = 187] = "NewExpression";
- SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 188] = "TaggedTemplateExpression";
- SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 189] = "TypeAssertionExpression";
- SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 190] = "ParenthesizedExpression";
- SyntaxKind[SyntaxKind["FunctionExpression"] = 191] = "FunctionExpression";
- SyntaxKind[SyntaxKind["ArrowFunction"] = 192] = "ArrowFunction";
- SyntaxKind[SyntaxKind["DeleteExpression"] = 193] = "DeleteExpression";
- SyntaxKind[SyntaxKind["TypeOfExpression"] = 194] = "TypeOfExpression";
- SyntaxKind[SyntaxKind["VoidExpression"] = 195] = "VoidExpression";
- SyntaxKind[SyntaxKind["AwaitExpression"] = 196] = "AwaitExpression";
- SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 197] = "PrefixUnaryExpression";
- SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 198] = "PostfixUnaryExpression";
- SyntaxKind[SyntaxKind["BinaryExpression"] = 199] = "BinaryExpression";
- SyntaxKind[SyntaxKind["ConditionalExpression"] = 200] = "ConditionalExpression";
- SyntaxKind[SyntaxKind["TemplateExpression"] = 201] = "TemplateExpression";
- SyntaxKind[SyntaxKind["YieldExpression"] = 202] = "YieldExpression";
- SyntaxKind[SyntaxKind["SpreadElement"] = 203] = "SpreadElement";
- SyntaxKind[SyntaxKind["ClassExpression"] = 204] = "ClassExpression";
- SyntaxKind[SyntaxKind["OmittedExpression"] = 205] = "OmittedExpression";
- SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 206] = "ExpressionWithTypeArguments";
- SyntaxKind[SyntaxKind["AsExpression"] = 207] = "AsExpression";
- SyntaxKind[SyntaxKind["NonNullExpression"] = 208] = "NonNullExpression";
- SyntaxKind[SyntaxKind["MetaProperty"] = 209] = "MetaProperty";
- SyntaxKind[SyntaxKind["TemplateSpan"] = 210] = "TemplateSpan";
- SyntaxKind[SyntaxKind["SemicolonClassElement"] = 211] = "SemicolonClassElement";
- SyntaxKind[SyntaxKind["Block"] = 212] = "Block";
- SyntaxKind[SyntaxKind["VariableStatement"] = 213] = "VariableStatement";
- SyntaxKind[SyntaxKind["EmptyStatement"] = 214] = "EmptyStatement";
- SyntaxKind[SyntaxKind["ExpressionStatement"] = 215] = "ExpressionStatement";
- SyntaxKind[SyntaxKind["IfStatement"] = 216] = "IfStatement";
- SyntaxKind[SyntaxKind["DoStatement"] = 217] = "DoStatement";
- SyntaxKind[SyntaxKind["WhileStatement"] = 218] = "WhileStatement";
- SyntaxKind[SyntaxKind["ForStatement"] = 219] = "ForStatement";
- SyntaxKind[SyntaxKind["ForInStatement"] = 220] = "ForInStatement";
- SyntaxKind[SyntaxKind["ForOfStatement"] = 221] = "ForOfStatement";
- SyntaxKind[SyntaxKind["ContinueStatement"] = 222] = "ContinueStatement";
- SyntaxKind[SyntaxKind["BreakStatement"] = 223] = "BreakStatement";
- SyntaxKind[SyntaxKind["ReturnStatement"] = 224] = "ReturnStatement";
- SyntaxKind[SyntaxKind["WithStatement"] = 225] = "WithStatement";
- SyntaxKind[SyntaxKind["SwitchStatement"] = 226] = "SwitchStatement";
- SyntaxKind[SyntaxKind["LabeledStatement"] = 227] = "LabeledStatement";
- SyntaxKind[SyntaxKind["ThrowStatement"] = 228] = "ThrowStatement";
- SyntaxKind[SyntaxKind["TryStatement"] = 229] = "TryStatement";
- SyntaxKind[SyntaxKind["DebuggerStatement"] = 230] = "DebuggerStatement";
- SyntaxKind[SyntaxKind["VariableDeclaration"] = 231] = "VariableDeclaration";
- SyntaxKind[SyntaxKind["VariableDeclarationList"] = 232] = "VariableDeclarationList";
- SyntaxKind[SyntaxKind["FunctionDeclaration"] = 233] = "FunctionDeclaration";
- SyntaxKind[SyntaxKind["ClassDeclaration"] = 234] = "ClassDeclaration";
- SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 235] = "InterfaceDeclaration";
- SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 236] = "TypeAliasDeclaration";
- SyntaxKind[SyntaxKind["EnumDeclaration"] = 237] = "EnumDeclaration";
- SyntaxKind[SyntaxKind["ModuleDeclaration"] = 238] = "ModuleDeclaration";
- SyntaxKind[SyntaxKind["ModuleBlock"] = 239] = "ModuleBlock";
- SyntaxKind[SyntaxKind["CaseBlock"] = 240] = "CaseBlock";
- SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 241] = "NamespaceExportDeclaration";
- SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 242] = "ImportEqualsDeclaration";
- SyntaxKind[SyntaxKind["ImportDeclaration"] = 243] = "ImportDeclaration";
- SyntaxKind[SyntaxKind["ImportClause"] = 244] = "ImportClause";
- SyntaxKind[SyntaxKind["NamespaceImport"] = 245] = "NamespaceImport";
- SyntaxKind[SyntaxKind["NamedImports"] = 246] = "NamedImports";
- SyntaxKind[SyntaxKind["ImportSpecifier"] = 247] = "ImportSpecifier";
- SyntaxKind[SyntaxKind["ExportAssignment"] = 248] = "ExportAssignment";
- SyntaxKind[SyntaxKind["ExportDeclaration"] = 249] = "ExportDeclaration";
- SyntaxKind[SyntaxKind["NamedExports"] = 250] = "NamedExports";
- SyntaxKind[SyntaxKind["ExportSpecifier"] = 251] = "ExportSpecifier";
- SyntaxKind[SyntaxKind["MissingDeclaration"] = 252] = "MissingDeclaration";
- SyntaxKind[SyntaxKind["ExternalModuleReference"] = 253] = "ExternalModuleReference";
- SyntaxKind[SyntaxKind["JsxElement"] = 254] = "JsxElement";
- SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 255] = "JsxSelfClosingElement";
- SyntaxKind[SyntaxKind["JsxOpeningElement"] = 256] = "JsxOpeningElement";
- SyntaxKind[SyntaxKind["JsxClosingElement"] = 257] = "JsxClosingElement";
- SyntaxKind[SyntaxKind["JsxFragment"] = 258] = "JsxFragment";
- SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 259] = "JsxOpeningFragment";
- SyntaxKind[SyntaxKind["JsxClosingFragment"] = 260] = "JsxClosingFragment";
- SyntaxKind[SyntaxKind["JsxAttribute"] = 261] = "JsxAttribute";
- SyntaxKind[SyntaxKind["JsxAttributes"] = 262] = "JsxAttributes";
- SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 263] = "JsxSpreadAttribute";
- SyntaxKind[SyntaxKind["JsxExpression"] = 264] = "JsxExpression";
- SyntaxKind[SyntaxKind["CaseClause"] = 265] = "CaseClause";
- SyntaxKind[SyntaxKind["DefaultClause"] = 266] = "DefaultClause";
- SyntaxKind[SyntaxKind["HeritageClause"] = 267] = "HeritageClause";
- SyntaxKind[SyntaxKind["CatchClause"] = 268] = "CatchClause";
- SyntaxKind[SyntaxKind["PropertyAssignment"] = 269] = "PropertyAssignment";
- SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 270] = "ShorthandPropertyAssignment";
- SyntaxKind[SyntaxKind["SpreadAssignment"] = 271] = "SpreadAssignment";
- SyntaxKind[SyntaxKind["EnumMember"] = 272] = "EnumMember";
- SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle";
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression";
- SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType";
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag";
- SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList";
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker";
- SyntaxKind[SyntaxKind["Count"] = 300] = "Count";
- SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
- SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
- SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment";
- SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment";
- SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord";
- SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord";
- SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword";
- SyntaxKind[SyntaxKind["LastKeyword"] = 144] = "LastKeyword";
- SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord";
- SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord";
- SyntaxKind[SyntaxKind["FirstTypeNode"] = 160] = "FirstTypeNode";
- SyntaxKind[SyntaxKind["LastTypeNode"] = 178] = "LastTypeNode";
- SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation";
- SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation";
- SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
- SyntaxKind[SyntaxKind["LastToken"] = 144] = "LastToken";
- SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
- SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
- SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
- SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken";
- SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken";
- SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken";
- SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator";
- SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator";
- SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode";
- SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
- SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword";
- })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
- var NodeFlags;
- (function (NodeFlags) {
- NodeFlags[NodeFlags["None"] = 0] = "None";
- NodeFlags[NodeFlags["Let"] = 1] = "Let";
- NodeFlags[NodeFlags["Const"] = 2] = "Const";
- NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
- NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
- NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
- NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext";
- NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis";
- NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn";
- NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn";
- NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation";
- NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions";
- NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext";
- NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext";
- NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext";
- NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext";
- NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError";
- NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile";
- NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError";
- NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData";
- NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport";
- NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta";
- NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
- NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
- NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
- NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
- NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
- NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
- NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags";
- NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags";
- NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags";
- })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
- var ModifierFlags;
- (function (ModifierFlags) {
- ModifierFlags[ModifierFlags["None"] = 0] = "None";
- ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
- ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
- ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
- ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
- ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
- ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
- ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
- ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
- ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
- ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
- ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
- ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
- ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
- ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
- ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
- ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
- ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
- ModifierFlags[ModifierFlags["All"] = 3071] = "All";
- })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
- var JsxFlags;
- (function (JsxFlags) {
- JsxFlags[JsxFlags["None"] = 0] = "None";
- JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
- JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
- JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
- })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
- var RelationComparisonResult;
- (function (RelationComparisonResult) {
- RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
- RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
- RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported";
- })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
- var GeneratedIdentifierFlags;
- (function (GeneratedIdentifierFlags) {
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel";
- })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- var TokenFlags;
- (function (TokenFlags) {
- TokenFlags[TokenFlags["None"] = 0] = "None";
- TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
- TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
- TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
- TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
- TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
- TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
- TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
- TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
- TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
- TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
- TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
- TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
- })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
- var FlowFlags;
- (function (FlowFlags) {
- FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
- FlowFlags[FlowFlags["Start"] = 2] = "Start";
- FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
- FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
- FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
- FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
- FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
- FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
- FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
- FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced";
- FlowFlags[FlowFlags["Shared"] = 1024] = "Shared";
- FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally";
- FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally";
- FlowFlags[FlowFlags["Label"] = 12] = "Label";
- FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
- })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
var OperationCanceledException = (function () {
function OperationCanceledException() {
}
return OperationCanceledException;
}());
ts.OperationCanceledException = OperationCanceledException;
- var StructureIsReused;
- (function (StructureIsReused) {
- StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
- StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
- StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
- })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
var ExitStatus;
(function (ExitStatus) {
ExitStatus[ExitStatus["Success"] = 0] = "Success";
ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
})(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
- var UnionReduction;
- (function (UnionReduction) {
- UnionReduction[UnionReduction["None"] = 0] = "None";
- UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
- UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
- })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
- var NodeBuilderFlags;
- (function (NodeBuilderFlags) {
- NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
- NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
- NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
- NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
- NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
- NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
- NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
- NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
- NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
- NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
- NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
- NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
- NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
- NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
- NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
- NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
- NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
- NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
- NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
- NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
- NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
- NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
- NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
- NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
- NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
- })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
- var TypeFormatFlags;
- (function (TypeFormatFlags) {
- TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
- TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
- TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
- TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
- TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
- TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
- TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
- TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
- TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
- TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
- TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
- TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
- TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
- TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
- TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
- TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
- TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
- TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
- TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
- TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask";
- })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
- var SymbolFormatFlags;
- (function (SymbolFormatFlags) {
- SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
- SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
- SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
- SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
- SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
- })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
- var SymbolAccessibility;
- (function (SymbolAccessibility) {
- SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
- SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
- SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
- })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
- var SyntheticSymbolKind;
- (function (SyntheticSymbolKind) {
- SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
- SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
- })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
- var TypePredicateKind;
- (function (TypePredicateKind) {
- TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
- TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
- })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
var TypeReferenceSerializationKind;
(function (TypeReferenceSerializationKind) {
TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
@@ -606,269 +60,6 @@ var ts;
TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature";
TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType";
})(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
- var SymbolFlags;
- (function (SymbolFlags) {
- SymbolFlags[SymbolFlags["None"] = 0] = "None";
- SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
- SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
- SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
- SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
- SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
- SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
- SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
- SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
- SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
- SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
- SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
- SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
- SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
- SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
- SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
- SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
- SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
- SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
- SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
- SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
- SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
- SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
- SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
- SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
- SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
- SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
- SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer";
- SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
- SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
- SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
- SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value";
- SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type";
- SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
- SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
- SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
- SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes";
- SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes";
- SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes";
- SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
- SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes";
- SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes";
- SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes";
- SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes";
- SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes";
- SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes";
- SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes";
- SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
- SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes";
- SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes";
- SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes";
- SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes";
- SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes";
- SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
- SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
- SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
- SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports";
- SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers";
- SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
- SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
- SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
- SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
- SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer";
- })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
- var EnumKind;
- (function (EnumKind) {
- EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
- EnumKind[EnumKind["Literal"] = 1] = "Literal";
- })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
- var CheckFlags;
- (function (CheckFlags) {
- CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
- CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
- CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
- CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
- CheckFlags[CheckFlags["Partial"] = 16] = "Partial";
- CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType";
- CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic";
- CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected";
- CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate";
- CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic";
- CheckFlags[CheckFlags["Late"] = 1024] = "Late";
- CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped";
- CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
- })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
- var InternalSymbolName;
- (function (InternalSymbolName) {
- InternalSymbolName["Call"] = "__call";
- InternalSymbolName["Constructor"] = "__constructor";
- InternalSymbolName["New"] = "__new";
- InternalSymbolName["Index"] = "__index";
- InternalSymbolName["ExportStar"] = "__export";
- InternalSymbolName["Global"] = "__global";
- InternalSymbolName["Missing"] = "__missing";
- InternalSymbolName["Type"] = "__type";
- InternalSymbolName["Object"] = "__object";
- InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
- InternalSymbolName["Class"] = "__class";
- InternalSymbolName["Function"] = "__function";
- InternalSymbolName["Computed"] = "__computed";
- InternalSymbolName["Resolving"] = "__resolving__";
- InternalSymbolName["ExportEquals"] = "export=";
- InternalSymbolName["Default"] = "default";
- })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
- var NodeCheckFlags;
- (function (NodeCheckFlags) {
- NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
- NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
- NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
- NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
- NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
- NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
- NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
- NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
- NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
- NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
- NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
- NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
- NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
- NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding";
- NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop";
- NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding";
- NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding";
- NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter";
- NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked";
- NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference";
- NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass";
- })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
- var TypeFlags;
- (function (TypeFlags) {
- TypeFlags[TypeFlags["Any"] = 1] = "Any";
- TypeFlags[TypeFlags["String"] = 2] = "String";
- TypeFlags[TypeFlags["Number"] = 4] = "Number";
- TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean";
- TypeFlags[TypeFlags["Enum"] = 16] = "Enum";
- TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral";
- TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral";
- TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral";
- TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral";
- TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol";
- TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol";
- TypeFlags[TypeFlags["Void"] = 2048] = "Void";
- TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined";
- TypeFlags[TypeFlags["Null"] = 8192] = "Null";
- TypeFlags[TypeFlags["Never"] = 16384] = "Never";
- TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter";
- TypeFlags[TypeFlags["Object"] = 65536] = "Object";
- TypeFlags[TypeFlags["Union"] = 131072] = "Union";
- TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection";
- TypeFlags[TypeFlags["Index"] = 524288] = "Index";
- TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess";
- TypeFlags[TypeFlags["Conditional"] = 2097152] = "Conditional";
- TypeFlags[TypeFlags["Substitution"] = 4194304] = "Substitution";
- TypeFlags[TypeFlags["FreshLiteral"] = 8388608] = "FreshLiteral";
- TypeFlags[TypeFlags["ContainsWideningType"] = 16777216] = "ContainsWideningType";
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 33554432] = "ContainsObjectLiteral";
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType";
- TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive";
- TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType";
- TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable";
- TypeFlags[TypeFlags["Literal"] = 224] = "Literal";
- TypeFlags[TypeFlags["Unit"] = 13536] = "Unit";
- TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral";
- TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique";
- TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy";
- TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy";
- TypeFlags[TypeFlags["Intrinsic"] = 134249103] = "Intrinsic";
- TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive";
- TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike";
- TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike";
- TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike";
- TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike";
- TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike";
- TypeFlags[TypeFlags["VoidLike"] = 6144] = "VoidLike";
- TypeFlags[TypeFlags["DisjointDomains"] = 134233854] = "DisjointDomains";
- TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection";
- TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType";
- TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable";
- TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 7372800] = "InstantiableNonPrimitive";
- TypeFlags[TypeFlags["InstantiablePrimitive"] = 524288] = "InstantiablePrimitive";
- TypeFlags[TypeFlags["Instantiable"] = 7897088] = "Instantiable";
- TypeFlags[TypeFlags["StructuredOrInstantiable"] = 8355840] = "StructuredOrInstantiable";
- TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable";
- TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit";
- TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening";
- TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags";
- TypeFlags[TypeFlags["NonWideningType"] = 16777216] = "NonWideningType";
- TypeFlags[TypeFlags["Wildcard"] = 33554432] = "Wildcard";
- TypeFlags[TypeFlags["EmptyObject"] = 67108864] = "EmptyObject";
- TypeFlags[TypeFlags["ConstructionFlags"] = 117440512] = "ConstructionFlags";
- })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
- var ObjectFlags;
- (function (ObjectFlags) {
- ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
- ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
- ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
- ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
- ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
- ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
- ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
- ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
- ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
- ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
- ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
- ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
- ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
- ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
- ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
- })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
- var Variance;
- (function (Variance) {
- Variance[Variance["Invariant"] = 0] = "Invariant";
- Variance[Variance["Covariant"] = 1] = "Covariant";
- Variance[Variance["Contravariant"] = 2] = "Contravariant";
- Variance[Variance["Bivariant"] = 3] = "Bivariant";
- Variance[Variance["Independent"] = 4] = "Independent";
- })(Variance = ts.Variance || (ts.Variance = {}));
- var SignatureKind;
- (function (SignatureKind) {
- SignatureKind[SignatureKind["Call"] = 0] = "Call";
- SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
- })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
- var IndexKind;
- (function (IndexKind) {
- IndexKind[IndexKind["String"] = 0] = "String";
- IndexKind[IndexKind["Number"] = 1] = "Number";
- })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
- var InferencePriority;
- (function (InferencePriority) {
- InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
- InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
- InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
- InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
- InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof";
- InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints";
- InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict";
- InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination";
- })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
- var InferenceFlags;
- (function (InferenceFlags) {
- InferenceFlags[InferenceFlags["None"] = 0] = "None";
- InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes";
- InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault";
- InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault";
- })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
- var Ternary;
- (function (Ternary) {
- Ternary[Ternary["False"] = 0] = "False";
- Ternary[Ternary["Maybe"] = 1] = "Maybe";
- Ternary[Ternary["True"] = -1] = "True";
- })(Ternary = ts.Ternary || (ts.Ternary = {}));
- var SpecialPropertyAssignmentKind;
- (function (SpecialPropertyAssignmentKind) {
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype";
- })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {}));
var DiagnosticCategory;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
@@ -897,390 +88,6 @@ var ts;
ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext";
})(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
- var JsxEmit;
- (function (JsxEmit) {
- JsxEmit[JsxEmit["None"] = 0] = "None";
- JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
- JsxEmit[JsxEmit["React"] = 2] = "React";
- JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
- })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
- var NewLineKind;
- (function (NewLineKind) {
- NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
- NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
- })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
- var ScriptKind;
- (function (ScriptKind) {
- ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
- ScriptKind[ScriptKind["JS"] = 1] = "JS";
- ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
- ScriptKind[ScriptKind["TS"] = 3] = "TS";
- ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
- ScriptKind[ScriptKind["External"] = 5] = "External";
- ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
- })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
- var ScriptTarget;
- (function (ScriptTarget) {
- ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
- ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
- ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
- ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
- ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
- ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
- })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
- var LanguageVariant;
- (function (LanguageVariant) {
- LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
- LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
- })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
- var WatchDirectoryFlags;
- (function (WatchDirectoryFlags) {
- WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
- WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
- })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
- var CharacterCodes;
- (function (CharacterCodes) {
- CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
- CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
- CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
- CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
- CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
- CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
- CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
- CharacterCodes[CharacterCodes["space"] = 32] = "space";
- CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
- CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
- CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
- CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
- CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
- CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
- CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
- CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
- CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
- CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
- CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
- CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
- CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
- CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
- CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
- CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
- CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
- CharacterCodes[CharacterCodes["_"] = 95] = "_";
- CharacterCodes[CharacterCodes["$"] = 36] = "$";
- CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
- CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
- CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
- CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
- CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
- CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
- CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
- CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
- CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
- CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
- CharacterCodes[CharacterCodes["a"] = 97] = "a";
- CharacterCodes[CharacterCodes["b"] = 98] = "b";
- CharacterCodes[CharacterCodes["c"] = 99] = "c";
- CharacterCodes[CharacterCodes["d"] = 100] = "d";
- CharacterCodes[CharacterCodes["e"] = 101] = "e";
- CharacterCodes[CharacterCodes["f"] = 102] = "f";
- CharacterCodes[CharacterCodes["g"] = 103] = "g";
- CharacterCodes[CharacterCodes["h"] = 104] = "h";
- CharacterCodes[CharacterCodes["i"] = 105] = "i";
- CharacterCodes[CharacterCodes["j"] = 106] = "j";
- CharacterCodes[CharacterCodes["k"] = 107] = "k";
- CharacterCodes[CharacterCodes["l"] = 108] = "l";
- CharacterCodes[CharacterCodes["m"] = 109] = "m";
- CharacterCodes[CharacterCodes["n"] = 110] = "n";
- CharacterCodes[CharacterCodes["o"] = 111] = "o";
- CharacterCodes[CharacterCodes["p"] = 112] = "p";
- CharacterCodes[CharacterCodes["q"] = 113] = "q";
- CharacterCodes[CharacterCodes["r"] = 114] = "r";
- CharacterCodes[CharacterCodes["s"] = 115] = "s";
- CharacterCodes[CharacterCodes["t"] = 116] = "t";
- CharacterCodes[CharacterCodes["u"] = 117] = "u";
- CharacterCodes[CharacterCodes["v"] = 118] = "v";
- CharacterCodes[CharacterCodes["w"] = 119] = "w";
- CharacterCodes[CharacterCodes["x"] = 120] = "x";
- CharacterCodes[CharacterCodes["y"] = 121] = "y";
- CharacterCodes[CharacterCodes["z"] = 122] = "z";
- CharacterCodes[CharacterCodes["A"] = 65] = "A";
- CharacterCodes[CharacterCodes["B"] = 66] = "B";
- CharacterCodes[CharacterCodes["C"] = 67] = "C";
- CharacterCodes[CharacterCodes["D"] = 68] = "D";
- CharacterCodes[CharacterCodes["E"] = 69] = "E";
- CharacterCodes[CharacterCodes["F"] = 70] = "F";
- CharacterCodes[CharacterCodes["G"] = 71] = "G";
- CharacterCodes[CharacterCodes["H"] = 72] = "H";
- CharacterCodes[CharacterCodes["I"] = 73] = "I";
- CharacterCodes[CharacterCodes["J"] = 74] = "J";
- CharacterCodes[CharacterCodes["K"] = 75] = "K";
- CharacterCodes[CharacterCodes["L"] = 76] = "L";
- CharacterCodes[CharacterCodes["M"] = 77] = "M";
- CharacterCodes[CharacterCodes["N"] = 78] = "N";
- CharacterCodes[CharacterCodes["O"] = 79] = "O";
- CharacterCodes[CharacterCodes["P"] = 80] = "P";
- CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
- CharacterCodes[CharacterCodes["R"] = 82] = "R";
- CharacterCodes[CharacterCodes["S"] = 83] = "S";
- CharacterCodes[CharacterCodes["T"] = 84] = "T";
- CharacterCodes[CharacterCodes["U"] = 85] = "U";
- CharacterCodes[CharacterCodes["V"] = 86] = "V";
- CharacterCodes[CharacterCodes["W"] = 87] = "W";
- CharacterCodes[CharacterCodes["X"] = 88] = "X";
- CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
- CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
- CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
- CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
- CharacterCodes[CharacterCodes["at"] = 64] = "at";
- CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
- CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
- CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
- CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
- CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
- CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
- CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
- CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
- CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
- CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
- CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
- CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
- CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
- CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
- CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
- CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
- CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
- CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
- CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
- CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
- CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
- CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
- CharacterCodes[CharacterCodes["question"] = 63] = "question";
- CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
- CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
- CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
- CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
- CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
- CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
- CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
- CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
- CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
- })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
- var Extension;
- (function (Extension) {
- Extension["Ts"] = ".ts";
- Extension["Tsx"] = ".tsx";
- Extension["Dts"] = ".d.ts";
- Extension["Js"] = ".js";
- Extension["Jsx"] = ".jsx";
- Extension["Json"] = ".json";
- })(Extension = ts.Extension || (ts.Extension = {}));
- var TransformFlags;
- (function (TransformFlags) {
- TransformFlags[TransformFlags["None"] = 0] = "None";
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
- TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators";
- TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments";
- TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread";
- TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread";
- TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest";
- TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 134217728] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper";
- TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes";
- TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask";
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask";
- })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
- var EmitFlags;
- (function (EmitFlags) {
- EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
- EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
- EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
- EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
- EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
- EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
- EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
- EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
- EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
- EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
- EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
- EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
- EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
- EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
- EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
- EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
- EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
- EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
- EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
- EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
- EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
- EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
- EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
- EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
- EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
- EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
- EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
- EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
- EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
- EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
- })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
- var ExternalEmitHelpers;
- (function (ExternalEmitHelpers) {
- ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
- ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
- ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
- ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
- ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
- ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
- ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
- ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
- ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
- ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
- ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
- ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
- ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
- ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject";
- ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
- ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper";
- ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
- })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
- var EmitHint;
- (function (EmitHint) {
- EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
- EmitHint[EmitHint["Expression"] = 1] = "Expression";
- EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
- EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
- EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
- })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
- var ListFormat;
- (function (ListFormat) {
- ListFormat[ListFormat["None"] = 0] = "None";
- ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
- ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
- ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
- ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
- ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
- ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
- ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
- ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
- ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask";
- ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma";
- ListFormat[ListFormat["Indented"] = 64] = "Indented";
- ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces";
- ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings";
- ListFormat[ListFormat["Braces"] = 512] = "Braces";
- ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis";
- ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets";
- ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets";
- ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask";
- ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined";
- ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty";
- ListFormat[ListFormat["Optional"] = 24576] = "Optional";
- ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine";
- ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine";
- ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments";
- ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty";
- ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement";
- ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers";
- ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses";
- ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers";
- ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers";
- ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements";
- ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents";
- ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents";
- ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements";
- ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements";
- ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties";
- ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements";
- ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements";
- ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments";
- ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments";
- ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans";
- ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements";
- ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements";
- ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList";
- ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements";
- ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
- ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
- ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers";
- ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers";
- ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers";
- ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses";
- ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements";
- ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren";
- ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes";
- ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements";
- ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes";
- ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements";
- ListFormat[ListFormat["Decorators"] = 24577] = "Decorators";
- ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments";
- ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters";
- ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
- ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
- })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
- var PragmaKindFlags;
- (function (PragmaKindFlags) {
- PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
- PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
- PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
- PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
- PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
- PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
- })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
function _contextuallyTypePragmas(args) {
return args;
}
@@ -1618,8 +425,8 @@ var ts;
return undefined;
}
ts.findLast = findLast;
- function findIndex(array, predicate) {
- for (var i = 0; i < array.length; i++) {
+ function findIndex(array, predicate, startIndex) {
+ for (var i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
@@ -1627,6 +434,15 @@ var ts;
return -1;
}
ts.findIndex = findIndex;
+ function findLastIndex(array, predicate, startIndex) {
+ for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
+ if (predicate(array[i], i)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ ts.findLastIndex = findLastIndex;
function findMap(array, callback) {
for (var i = 0; i < array.length; i++) {
var result = callback(array[i], i);
@@ -1957,6 +773,23 @@ var ts;
return false;
}
ts.some = some;
+ function getRangesWhere(arr, pred, cb) {
+ var start;
+ for (var i = 0; i < arr.length; i++) {
+ if (pred(arr[i])) {
+ start = start === undefined ? i : start;
+ }
+ else {
+ if (start !== undefined) {
+ cb(start, i);
+ start = undefined;
+ }
+ }
+ }
+ if (start !== undefined)
+ cb(start, arr.length);
+ }
+ ts.getRangesWhere = getRangesWhere;
function concatenate(array1, array2) {
if (!some(array2))
return array1;
@@ -2147,6 +980,15 @@ var ts;
return to;
}
ts.addRange = addRange;
+ function prependRange(to, from) {
+ if (from === undefined || from.length === 0)
+ return to;
+ if (to === undefined)
+ return from.slice();
+ to.unshift.apply(to, from);
+ return to;
+ }
+ ts.prependRange = prependRange;
function pushIfUnique(array, toAdd, equalityComparer) {
if (contains(array, toAdd, equalityComparer)) {
return false;
@@ -2344,17 +1186,18 @@ var ts;
}
ts.getOwnValues = getOwnValues;
function arrayFrom(iterator, map) {
+ var _a;
var result = [];
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
result.push(map ? map(value) : value);
}
return result;
- var _b;
}
ts.arrayFrom = arrayFrom;
function forEachEntry(map, callback) {
+ var _a;
var iterator = map.entries();
- for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
var key = pair[0], value = pair[1];
var result = callback(value, key);
if (result) {
@@ -2362,19 +1205,18 @@ var ts;
}
}
return undefined;
- var _b;
}
ts.forEachEntry = forEachEntry;
function forEachKey(map, callback) {
+ var _a;
var iterator = map.keys();
- for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
var result = callback(key);
if (result) {
return result;
}
}
return undefined;
- var _b;
}
ts.forEachKey = forEachKey;
function copyEntries(source, target) {
@@ -2843,11 +1685,11 @@ var ts;
comparer(a[key], b[key]);
}
ts.compareProperties = compareProperties;
- function getDiagnosticFileName(diagnostic) {
- return diagnostic.file ? diagnostic.file.fileName : undefined;
+ function getDiagnosticFilePath(diagnostic) {
+ return diagnostic.file ? diagnostic.file.path : undefined;
}
function compareDiagnostics(d1, d2) {
- return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
+ return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
@@ -2875,90 +1717,6 @@ var ts;
}
return text1 ? 1 : -1;
}
- function normalizeSlashes(path) {
- return path.replace(/\\/g, "/");
- }
- ts.normalizeSlashes = normalizeSlashes;
- function getRootLength(path) {
- if (path.charCodeAt(0) === 47) {
- if (path.charCodeAt(1) !== 47)
- return 1;
- var p1 = path.indexOf("/", 2);
- if (p1 < 0)
- return 2;
- var p2 = path.indexOf("/", p1 + 1);
- if (p2 < 0)
- return p1 + 1;
- return p2 + 1;
- }
- if (path.charCodeAt(1) === 58) {
- if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92)
- return 3;
- }
- if (path.lastIndexOf("file:///", 0) === 0) {
- return "file:///".length;
- }
- var idx = path.indexOf("://");
- if (idx !== -1) {
- return idx + "://".length;
- }
- return 0;
- }
- ts.getRootLength = getRootLength;
- ts.directorySeparator = "/";
- var directorySeparatorCharCode = 47;
- function getNormalizedParts(normalizedSlashedPath, rootLength) {
- var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator);
- var normalized = [];
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
- var part = parts_1[_i];
- if (part !== ".") {
- if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") {
- normalized.pop();
- }
- else {
- if (part) {
- normalized.push(part);
- }
- }
- }
- }
- return normalized;
- }
- function normalizePath(path) {
- return normalizePathAndParts(path).path;
- }
- ts.normalizePath = normalizePath;
- function normalizePathAndParts(path) {
- path = normalizeSlashes(path);
- var rootLength = getRootLength(path);
- var root = path.substr(0, rootLength);
- var parts = getNormalizedParts(path, rootLength);
- if (parts.length) {
- var joinedParts = root + parts.join(ts.directorySeparator);
- return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts };
- }
- else {
- return { path: root, parts: parts };
- }
- }
- ts.normalizePathAndParts = normalizePathAndParts;
- function pathEndsWithDirectorySeparator(path) {
- return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
- }
- ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator;
- function getDirectoryPath(path) {
- return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator)));
- }
- ts.getDirectoryPath = getDirectoryPath;
- function isUrl(path) {
- return path && !isRootedDiskPath(path) && stringContains(path, "://");
- }
- ts.isUrl = isUrl;
- function pathIsRelative(path) {
- return /^\.\.?($|[\\/])/.test(path);
- }
- ts.pathIsRelative = pathIsRelative;
function getEmitScriptTarget(compilerOptions) {
return compilerOptions.target || 0;
}
@@ -2990,6 +1748,10 @@ var ts;
: moduleKind === ts.ModuleKind.System;
}
ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
+ function getEmitDeclarations(compilerOptions) {
+ return !!(compilerOptions.declaration || compilerOptions.composite);
+ }
+ ts.getEmitDeclarations = getEmitDeclarations;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
}
@@ -3009,181 +1771,351 @@ var ts;
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ ts.directorySeparator = "/";
+ var altDirectorySeparator = "\\";
+ var urlSchemeSeparator = "://";
+ var backslashRegExp = /\\/g;
+ function normalizeSlashes(path) {
+ return path.replace(backslashRegExp, ts.directorySeparator);
+ }
+ ts.normalizeSlashes = normalizeSlashes;
+ function isVolumeCharacter(charCode) {
+ return (charCode >= 97 && charCode <= 122) ||
+ (charCode >= 65 && charCode <= 90);
+ }
+ function getFileUrlVolumeSeparatorEnd(url, start) {
+ var ch0 = url.charCodeAt(start);
+ if (ch0 === 58)
+ return start + 1;
+ if (ch0 === 37 && url.charCodeAt(start + 1) === 51) {
+ var ch2 = url.charCodeAt(start + 2);
+ if (ch2 === 97 || ch2 === 65)
+ return start + 3;
+ }
+ return -1;
+ }
+ function getEncodedRootLength(path) {
+ if (!path)
+ return 0;
+ var ch0 = path.charCodeAt(0);
+ if (ch0 === 47 || ch0 === 92) {
+ if (path.charCodeAt(1) !== ch0)
+ return 1;
+ var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2);
+ if (p1 < 0)
+ return path.length;
+ return p1 + 1;
+ }
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) {
+ var ch2 = path.charCodeAt(2);
+ if (ch2 === 47 || ch2 === 92)
+ return 3;
+ if (path.length === 2)
+ return 2;
+ }
+ var schemeEnd = path.indexOf(urlSchemeSeparator);
+ if (schemeEnd !== -1) {
+ var authorityStart = schemeEnd + urlSchemeSeparator.length;
+ var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
+ if (authorityEnd !== -1) {
+ var scheme = path.slice(0, schemeEnd);
+ var authority = path.slice(authorityStart, authorityEnd);
+ if (scheme === "file" && (authority === "" || authority === "localhost") &&
+ isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
+ var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
+ if (volumeSeparatorEnd !== -1) {
+ if (path.charCodeAt(volumeSeparatorEnd) === 47) {
+ return ~(volumeSeparatorEnd + 1);
+ }
+ if (volumeSeparatorEnd === path.length) {
+ return ~volumeSeparatorEnd;
+ }
+ }
+ }
+ return ~(authorityEnd + 1);
+ }
+ return ~path.length;
+ }
+ return 0;
+ }
+ function getRootLength(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength < 0 ? ~rootLength : rootLength;
+ }
+ ts.getRootLength = getRootLength;
+ function normalizePath(path) {
+ return resolvePath(path);
+ }
+ ts.normalizePath = normalizePath;
+ function normalizePathAndParts(path) {
+ path = normalizeSlashes(path);
+ var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
+ if (parts.length) {
+ var joinedParts = root + parts.join(ts.directorySeparator);
+ return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
+ }
+ else {
+ return { path: root, parts: parts };
+ }
+ }
+ ts.normalizePathAndParts = normalizePathAndParts;
+ function getDirectoryPath(path) {
+ path = normalizeSlashes(path);
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return path;
+ path = removeTrailingDirectorySeparator(path);
+ return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
+ }
+ ts.getDirectoryPath = getDirectoryPath;
+ function isUrl(path) {
+ return getEncodedRootLength(path) < 0;
+ }
+ ts.isUrl = isUrl;
+ function pathIsRelative(path) {
+ return /^\.\.?($|[\\/])/.test(path);
+ }
+ ts.pathIsRelative = pathIsRelative;
function isRootedDiskPath(path) {
- return path && getRootLength(path) !== 0;
+ return getEncodedRootLength(path) > 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
+ function isDiskPathRoot(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength > 0 && rootLength === path.length;
+ }
+ ts.isDiskPathRoot = isDiskPathRoot;
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
}
ts.convertToRelativePath = convertToRelativePath;
- function normalizedPathComponents(path, rootLength) {
- var normalizedParts = getNormalizedParts(path, rootLength);
- return [path.substr(0, rootLength)].concat(normalizedParts);
+ function pathComponents(path, rootLength) {
+ var root = path.substring(0, rootLength);
+ var rest = path.substring(rootLength).split(ts.directorySeparator);
+ if (rest.length && !lastOrUndefined(rest))
+ rest.pop();
+ return [root].concat(rest);
}
- function getNormalizedPathComponents(path, currentDirectory) {
- path = normalizeSlashes(path);
+ function getPathComponents(path, currentDirectory) {
+ if (currentDirectory === void 0) { currentDirectory = ""; }
+ path = combinePaths(currentDirectory, path);
var rootLength = getRootLength(path);
- if (rootLength === 0) {
- path = combinePaths(normalizeSlashes(currentDirectory), path);
- rootLength = getRootLength(path);
+ return pathComponents(path, rootLength);
+ }
+ ts.getPathComponents = getPathComponents;
+ function reducePathComponents(components) {
+ if (!some(components))
+ return [];
+ var reduced = [components[0]];
+ for (var i = 1; i < components.length; i++) {
+ var component = components[i];
+ if (!component)
+ continue;
+ if (component === ".")
+ continue;
+ if (component === "..") {
+ if (reduced.length > 1) {
+ if (reduced[reduced.length - 1] !== "..") {
+ reduced.pop();
+ continue;
+ }
+ }
+ else if (reduced[0])
+ continue;
+ }
+ reduced.push(component);
}
- return normalizedPathComponents(path, rootLength);
+ return reduced;
+ }
+ ts.reducePathComponents = reducePathComponents;
+ function getNormalizedPathComponents(path, currentDirectory) {
+ return reducePathComponents(getPathComponents(path, currentDirectory));
}
ts.getNormalizedPathComponents = getNormalizedPathComponents;
function getNormalizedAbsolutePath(fileName, currentDirectory) {
- return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
+ return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
- function getNormalizedPathFromPathComponents(pathComponents) {
- if (pathComponents && pathComponents.length) {
- return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator);
- }
+ function getPathFromPathComponents(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
+ if (pathComponents.length === 1)
+ return root;
+ return root + pathComponents.slice(1).join(ts.directorySeparator);
}
- ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents;
- function getNormalizedPathComponentsOfUrl(url) {
- var urlLength = url.length;
- var rootLength = url.indexOf("://") + "://".length;
- while (rootLength < urlLength) {
- if (url.charCodeAt(rootLength) === 47) {
- rootLength++;
- }
- else {
+ ts.getPathFromPathComponents = getPathFromPathComponents;
+ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
+ var fromComponents = reducePathComponents(getPathComponents(from));
+ var toComponents = reducePathComponents(getPathComponents(to));
+ var start;
+ for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
+ var fromComponent = getCanonicalFileName(fromComponents[start]);
+ var toComponent = getCanonicalFileName(toComponents[start]);
+ var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
+ if (!comparer(fromComponent, toComponent))
break;
- }
}
- if (rootLength === urlLength) {
- return [url];
+ if (start === 0) {
+ return toComponents;
}
- var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength);
- if (indexOfNextSlash !== -1) {
- rootLength = indexOfNextSlash + 1;
- return normalizedPathComponents(url, rootLength);
- }
- else {
- return [url + ts.directorySeparator];
+ var components = toComponents.slice(start);
+ var relative = [];
+ for (; start < fromComponents.length; start++) {
+ relative.push("..");
}
+ return [""].concat(relative, components);
}
- function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) {
- if (isUrl(pathOrUrl)) {
- return getNormalizedPathComponentsOfUrl(pathOrUrl);
- }
- else {
- return getNormalizedPathComponents(pathOrUrl, currentDirectory);
- }
+ function getRelativePathFromFile(from, to, getCanonicalFileName) {
+ return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
+ ts.getRelativePathFromFile = getRelativePathFromFile;
+ function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
+ Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
+ var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
+ var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
+ var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
- var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
- var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
- if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
- directoryComponents.pop();
+ var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName);
+ var firstComponent = pathComponents[0];
+ if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
+ var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
+ pathComponents[0] = prefix + firstComponent;
}
- var joinStartIndex;
- for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
- break;
- }
- }
- if (joinStartIndex) {
- var relativePath = "";
- var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length);
- for (; joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (directoryComponents[joinStartIndex] !== "") {
- relativePath = relativePath + ".." + ts.directorySeparator;
- }
- }
- return relativePath + relativePathComponents.join(ts.directorySeparator);
- }
- var absolutePath = getNormalizedPathFromPathComponents(pathComponents);
- if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) {
- absolutePath = "file:///" + absolutePath;
- }
- return absolutePath;
+ return getPathFromPathComponents(pathComponents);
}
ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
- function getRelativePath(path, directoryPath, getCanonicalFileName) {
- var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false);
- return ensurePathIsRelative(relativePath);
+ function ensurePathIsNonModuleName(path) {
+ return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path;
}
- ts.getRelativePath = getRelativePath;
- function ensurePathIsRelative(path) {
- return !pathIsRelative(path) ? "./" + path : path;
- }
- ts.ensurePathIsRelative = ensurePathIsRelative;
- function getBaseFileName(path) {
- if (path === undefined) {
- return undefined;
- }
- var i = path.lastIndexOf(ts.directorySeparator);
- return i < 0 ? path : path.substring(i + 1);
+ ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
+ function getBaseFileName(path, extensions, ignoreCase) {
+ path = normalizeSlashes(path);
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return "";
+ path = removeTrailingDirectorySeparator(path);
+ var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
+ var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
+ return extension ? name.slice(0, name.length - extension.length) : name;
}
ts.getBaseFileName = getBaseFileName;
- function combinePaths(path1, path2) {
- if (!(path1 && path1.length))
- return path2;
- if (!(path2 && path2.length))
- return path1;
- if (getRootLength(path2) !== 0)
- return path2;
- if (path1.charAt(path1.length - 1) === ts.directorySeparator)
- return path1 + path2;
- return path1 + ts.directorySeparator + path2;
+ function combinePaths(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ if (path)
+ path = normalizeSlashes(path);
+ for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
+ var relativePath = paths_1[_a];
+ if (!relativePath)
+ continue;
+ relativePath = normalizeSlashes(relativePath);
+ if (!path || getRootLength(relativePath) !== 0) {
+ path = relativePath;
+ }
+ else {
+ path = ensureTrailingDirectorySeparator(path) + relativePath;
+ }
+ }
+ return path;
}
ts.combinePaths = combinePaths;
+ function resolvePath(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path);
+ var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
+ return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
+ }
+ ts.resolvePath = resolvePath;
+ function hasTrailingDirectorySeparator(path) {
+ if (path.length === 0)
+ return false;
+ var ch = path.charCodeAt(path.length - 1);
+ return ch === 47 || ch === 92;
+ }
+ ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function removeTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) === ts.directorySeparator) {
+ if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
function ensureTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) !== ts.directorySeparator) {
+ if (!hasTrailingDirectorySeparator(path)) {
return path + ts.directorySeparator;
}
return path;
}
ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
- function comparePaths(a, b, currentDirectory, ignoreCase) {
+ function comparePathsWorker(a, b, componentComparer) {
if (a === b)
return 0;
if (a === undefined)
return -1;
if (b === undefined)
return 1;
- a = removeTrailingDirectorySeparator(a);
- b = removeTrailingDirectorySeparator(b);
- var aComponents = getNormalizedPathComponents(a, currentDirectory);
- var bComponents = getNormalizedPathComponents(b, currentDirectory);
+ var aComponents = reducePathComponents(getPathComponents(a));
+ var bComponents = reducePathComponents(getPathComponents(b));
var sharedLength = Math.min(aComponents.length, bComponents.length);
- var comparer = getStringComparer(ignoreCase);
for (var i = 0; i < sharedLength; i++) {
- var result = comparer(aComponents[i], bComponents[i]);
+ var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer;
+ var result = stringComparer(aComponents[i], bComponents[i]);
if (result !== 0) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
+ function comparePathsCaseSensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseSensitive);
+ }
+ ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ function comparePathsCaseInsensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseInsensitive);
+ }
+ ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
+ function comparePaths(a, b, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ a = combinePaths(currentDirectory, a);
+ b = combinePaths(currentDirectory, b);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
+ return comparePathsWorker(a, b, getStringComparer(ignoreCase));
+ }
ts.comparePaths = comparePaths;
function containsPath(parent, child, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ parent = combinePaths(currentDirectory, parent);
+ child = combinePaths(currentDirectory, child);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
if (parent === undefined || child === undefined)
return false;
if (parent === child)
return true;
- parent = removeTrailingDirectorySeparator(parent);
- child = removeTrailingDirectorySeparator(child);
- if (parent === child)
- return true;
- var parentComponents = getNormalizedPathComponents(parent, currentDirectory);
- var childComponents = getNormalizedPathComponents(child, currentDirectory);
+ var parentComponents = reducePathComponents(getPathComponents(parent));
+ var childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
- var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
+ var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (var i = 0; i < parentComponents.length; i++) {
+ var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
@@ -3460,13 +2392,17 @@ var ts;
ts.supportedJavascriptExtensions = [".js", ".jsx"];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
- var needAllExtensions = options && options.allowJs;
- if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
- return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ var needJsExtensions = options && options.allowJs;
+ if (!extraFileExtensions || extraFileExtensions.length === 0) {
+ return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
- return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive);
+ var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
+ return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
+ function isJavaScriptLike(scriptKind) {
+ return scriptKind === 1 || scriptKind === 2;
+ }
function hasJavaScriptFileExtension(fileName) {
return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}
@@ -3488,13 +2424,6 @@ var ts;
return false;
}
ts.isSupportedSourceFileName = isSupportedSourceFileName;
- var ExtensionPriority;
- (function (ExtensionPriority) {
- ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
- ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
- ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
- ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
- })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
function getExtensionPriority(path, supportedExtensions) {
for (var i = supportedExtensions.length - 1; i >= 0; i--) {
if (fileExtensionIs(path, supportedExtensions[i])) {
@@ -3525,7 +2454,7 @@ var ts;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"];
+ var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx", ".json"];
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
@@ -3546,9 +2475,14 @@ var ts;
}
ts.removeExtension = removeExtension;
function changeExtension(path, newExtension) {
- return (removeFileExtension(path) + newExtension);
+ return changeAnyExtension(path, newExtension, extensionsToRemove, false);
}
ts.changeExtension = changeExtension;
+ function changeAnyExtension(path, ext, extensions, ignoreCase) {
+ var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
+ return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
+ }
+ ts.changeAnyExtension = changeAnyExtension;
function removeMinAndVersionNumbers(fileName) {
var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
@@ -3596,13 +2530,6 @@ var ts;
getSignatureConstructor: function () { return Signature; },
getSourceMapSourceConstructor: function () { return SourceMapSource; },
};
- var AssertionLevel;
- (function (AssertionLevel) {
- AssertionLevel[AssertionLevel["None"] = 0] = "None";
- AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
- AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
- AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
- })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
var Debug;
(function (Debug) {
Debug.currentAssertionLevel = 0;
@@ -3807,6 +2734,10 @@ var ts;
return ext === ".ts" || ext === ".tsx" || ext === ".d.ts";
}
ts.extensionIsTypeScript = extensionIsTypeScript;
+ function resolutionExtensionIsTypeScriptOrJson(ext) {
+ return extensionIsTypeScript(ext) || ext === ".json";
+ }
+ ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson;
function extensionFromPath(path) {
var ext = tryGetExtensionFromPath(path);
if (ext !== undefined) {
@@ -3823,12 +2754,32 @@ var ts;
return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); });
}
ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
- function getAnyExtensionFromPath(path) {
+ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
+ if (typeof extensions === "string")
+ extensions = [extensions];
+ for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
+ var extension = extensions_2[_i];
+ if (!startsWith(extension, "."))
+ extension = "." + extension;
+ if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
+ var pathExtension = path.slice(path.length - extension.length);
+ if (stringEqualityComparer(pathExtension, extension)) {
+ return pathExtension;
+ }
+ }
+ }
+ return "";
+ }
+ function getAnyExtensionFromPath(path, extensions, ignoreCase) {
+ if (extensions) {
+ return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
+ }
var baseFileName = getBaseFileName(path);
var extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
+ return "";
}
ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
@@ -3921,12 +2872,12 @@ var ts;
ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval;
ts.missingFileModifiedTime = new Date(0);
function createPollingIntervalBasedLevels(levels) {
+ var _a;
return _a = {},
_a[PollingInterval.Low] = levels.Low,
_a[PollingInterval.Medium] = levels.Medium,
_a[PollingInterval.High] = levels.High,
_a;
- var _a;
}
var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
@@ -4199,11 +3150,6 @@ var ts;
var isNode4OrLater = nodeVersion >= 4;
var platform = _os.platform();
var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
- var FileSystemEntryKind;
- (function (FileSystemEntryKind) {
- FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
- FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
- })(FileSystemEntryKind || (FileSystemEntryKind = {}));
var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER;
var tscWatchFile = process.env.TSC_WATCHFILE;
var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY;
@@ -4243,6 +3189,7 @@ var ts;
readDirectory: readDirectory,
getModifiedTime: getModifiedTime,
createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
+ createSHA256Hash: _crypto ? createSHA256Hash : undefined,
getMemoryUsage: function () {
if (global.gc) {
global.gc();
@@ -4615,6 +3562,11 @@ var ts;
hash.update(data);
return hash.digest("hex");
}
+ function createSHA256Hash(data) {
+ var hash = _crypto.createHash("sha256");
+ hash.update(data);
+ return hash.digest("hex");
+ }
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -4917,7 +3869,7 @@ var ts;
Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
- Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."),
+ Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
@@ -5394,6 +4346,7 @@ var ts;
Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
+ Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
@@ -5577,6 +4530,17 @@ var ts;
Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
_0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true),
+ Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
+ All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true),
+ Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
+ Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
+ Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
+ Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
+ Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
+ Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
+ File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
+ Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
+ Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
@@ -5675,6 +4639,7 @@ var ts;
Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
+ Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
@@ -5738,6 +4703,12 @@ var ts;
Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
+ Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
+ Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
+ Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
+ Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
+ Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
+ Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -5971,7 +4942,7 @@ var ts;
if (includeJsDoc && ts.hasJSDocNodes(node)) {
return getTokenPosOfNode(node.jsDoc[0]);
}
- if (node.kind === 294 && node._children.length > 0) {
+ if (node.kind === 298 && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -6146,12 +5117,12 @@ var ts;
case 159:
case 162:
case 163:
- case 281:
+ case 283:
case 234:
case 204:
case 235:
case 236:
- case 291:
+ case 295:
case 233:
case 153:
case 154:
@@ -6159,6 +5130,9 @@ var ts;
case 156:
case 191:
case 192:
+ case 291:
+ case 296:
+ case 287:
return true;
default:
ts.assertTypeIsNever(node);
@@ -6181,6 +5155,12 @@ var ts;
case 243:
case 242:
case 213:
+ case 234:
+ case 233:
+ case 238:
+ case 236:
+ case 235:
+ case 237:
return true;
default:
return false;
@@ -6192,13 +5172,7 @@ var ts;
}
ts.isAnyImportOrReExport = isAnyImportOrReExport;
function getEnclosingBlockScopeContainer(node) {
- var current = node.parent;
- while (current) {
- if (isBlockScope(current, current.parent)) {
- return current;
- }
- current = current.parent;
- }
+ return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
}
ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
function declarationNameToString(name) {
@@ -6308,6 +5282,8 @@ var ts;
case 155:
case 156:
case 236:
+ case 151:
+ case 150:
errorNode = node.name;
break;
case 192:
@@ -6335,6 +5311,10 @@ var ts;
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
+ function isJsonSourceFile(file) {
+ return file.scriptKind === 6;
+ }
+ ts.isJsonSourceFile = isJsonSourceFile;
function isConstEnumDeclaration(node) {
return node.kind === 237 && isConst(node);
}
@@ -6646,6 +5626,23 @@ var ts;
});
}
ts.getPropertyAssignment = getPropertyAssignment;
+ function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
+ if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
+ var expression = tsConfigSourceFile.statements[0].expression;
+ return ts.isObjectLiteralExpression(expression) && expression;
+ }
+ }
+ ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
+ function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
+ var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
+ return jsonObjectLiteral &&
+ ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
function getContainingFunction(node) {
return ts.findAncestor(node.parent, ts.isFunctionLike);
}
@@ -6983,6 +5980,10 @@ var ts;
return node && !!(node.flags & 65536);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isInJsonFile(node) {
+ return node && !!(node.flags & 16777216);
+ }
+ ts.isInJsonFile = isInJsonFile;
function isInJSDoc(node) {
return node && !!(node.flags & 2097152);
}
@@ -7160,6 +6161,10 @@ var ts;
}
ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
function importFromModuleSpecifier(node) {
+ return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
+ }
+ ts.importFromModuleSpecifier = importFromModuleSpecifier;
+ function tryGetImportFromModuleSpecifier(node) {
switch (node.parent.kind) {
case 243:
case 249:
@@ -7169,12 +6174,13 @@ var ts;
case 186:
return node.parent;
case 177:
- return ts.cast(node.parent.parent, ts.isImportTypeNode);
+ ts.Debug.assert(ts.isStringLiteral(node));
+ return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
default:
- return ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent));
+ return undefined;
}
}
- ts.importFromModuleSpecifier = importFromModuleSpecifier;
+ ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
function getExternalModuleName(node) {
switch (node.kind) {
case 243:
@@ -7223,12 +6229,20 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 281 &&
+ return node.kind === 283 &&
node.parameters.length > 0 &&
node.parameters[0].name &&
node.parameters[0].name.escapedText === "new";
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
+ function isJSDocTypeAlias(node) {
+ return node.kind === 296 || node.kind === 291;
+ }
+ ts.isJSDocTypeAlias = isJSDocTypeAlias;
+ function isTypeAlias(node) {
+ return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
+ }
+ ts.isTypeAlias = isTypeAlias;
function getSourceOfAssignment(node) {
return ts.isExpressionStatement(node) &&
node.expression && ts.isBinaryExpression(node.expression) &&
@@ -7250,6 +6264,8 @@ var ts;
return v && v.initializer;
case 151:
return node.initializer;
+ case 269:
+ return node.initializer;
}
}
function getSingleVariableOfVariableStatement(node) {
@@ -7263,9 +6279,9 @@ var ts;
node.body.kind === 238 &&
node.body;
}
- function getJSDocCommentsAndTags(node) {
+ function getJSDocCommentsAndTags(hostNode) {
var result;
- getJSDocCommentsAndTagsWorker(node);
+ getJSDocCommentsAndTagsWorker(hostNode);
return result || ts.emptyArray;
function getJSDocCommentsAndTagsWorker(node) {
var parent = node.parent;
@@ -7274,8 +6290,7 @@ var ts;
if (parent.kind === 269 || parent.kind === 151 || getNestedModuleDeclaration(parent)) {
getJSDocCommentsAndTagsWorker(parent);
}
- if (parent.parent &&
- (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) {
+ if (parent.parent && (getSingleVariableOfVariableStatement(parent.parent) === node)) {
getJSDocCommentsAndTagsWorker(parent.parent);
}
if (parent.parent && parent.parent.parent &&
@@ -7284,15 +6299,15 @@ var ts;
getSourceOfDefaultedAssignment(parent.parent.parent))) {
getJSDocCommentsAndTagsWorker(parent.parent.parent);
}
- if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 ||
- ts.isBinaryExpression(parent) && getSpecialPropertyAssignmentKind(parent) !== 0 ||
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === 58 ||
+ ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 ||
node.kind === 184 && node.parent && node.parent.kind === 215) {
getJSDocCommentsAndTagsWorker(parent);
}
if (node.kind === 148) {
result = ts.addRange(result, ts.getJSDocParameterTags(node));
}
- if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) {
+ if (isVariableLike(node) && ts.hasInitializer(node) && node.initializer !== hostNode && ts.hasJSDocNodes(node.initializer)) {
result = ts.addRange(result, node.initializer.jsDoc);
}
if (ts.hasJSDocNodes(node)) {
@@ -7318,7 +6333,10 @@ var ts;
}
ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
function getHostSignatureFromJSDoc(node) {
- var host = getJSDocHost(node);
+ return getHostSignatureFromJSDocHost(getJSDocHost(node));
+ }
+ ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
+ function getHostSignatureFromJSDocHost(host) {
var decl = getSourceOfDefaultedAssignment(host) ||
getSourceOfAssignment(host) ||
getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
@@ -7327,18 +6345,9 @@ var ts;
host;
return decl && ts.isFunctionLike(decl) ? decl : undefined;
}
- ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
+ ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
- while (node.parent.kind === 284) {
- if (node.parent.parent.kind === 292) {
- node = node.parent.parent;
- }
- else {
- node = node.parent.parent.parent;
- }
- }
- ts.Debug.assert(node.parent.kind === 283);
- return node.parent.parent;
+ return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -7353,15 +6362,10 @@ var ts;
}
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
- return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282;
+ var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
+ return node.dotDotDotToken !== undefined || type && type.kind === 284;
}
ts.isRestParameter = isRestParameter;
- var AssignmentKind;
- (function (AssignmentKind) {
- AssignmentKind[AssignmentKind["None"] = 0] = "None";
- AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
- AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
- })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
function getAssignmentTargetKind(node) {
var parent = node.parent;
while (true) {
@@ -7484,8 +6488,14 @@ var ts;
if (ts.isDeclaration(name.parent)) {
return name.parent.name === name;
}
- var binExp = name.parent.parent;
- return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name;
+ else if (ts.isQualifiedName(name.parent)) {
+ var tag = name.parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === name.parent;
+ }
+ else {
+ var binExp = name.parent.parent;
+ return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name;
+ }
default:
return false;
}
@@ -7615,14 +6625,6 @@ var ts;
return 2 <= token && token <= 7;
}
ts.isTrivia = isTrivia;
- var FunctionFlags;
- (function (FunctionFlags) {
- FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
- FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
- FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
- FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
- FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
- })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
function getFunctionFlags(node) {
if (!node) {
return 4;
@@ -7770,11 +6772,6 @@ var ts;
return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
}
ts.getOriginalSourceFile = getOriginalSourceFile;
- var Associativity;
- (function (Associativity) {
- Associativity[Associativity["Left"] = 0] = "Left";
- Associativity[Associativity["Right"] = 1] = "Right";
- })(Associativity = ts.Associativity || (ts.Associativity = {}));
function getExpressionAssociativity(expression) {
var operator = getOperator(expression);
var hasArguments = expression.kind === 187 && expression.arguments !== undefined;
@@ -7835,7 +6832,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 297:
+ case 301:
return 0;
case 203:
return 1;
@@ -8146,8 +7143,8 @@ var ts;
};
}
ts.createTextWriter = createTextWriter;
- function getResolvedExternalModuleName(host, file) {
- return file.moduleName || getExternalModuleNameFromPath(host, file.fileName);
+ function getResolvedExternalModuleName(host, file, referenceFile) {
+ return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
}
ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
@@ -8158,12 +7155,13 @@ var ts;
return getResolvedExternalModuleName(host, file);
}
ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
- function getExternalModuleNameFromPath(host, fileName) {
+ function getExternalModuleNameFromPath(host, fileName, referencePath) {
var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
- var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
+ var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false);
- return ts.removeFileExtension(relativePath);
+ var extensionless = ts.removeFileExtension(relativePath);
+ return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
}
ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
function getOwnEmitOutputFilePath(sourceFile, host, extension) {
@@ -8245,7 +7243,7 @@ var ts;
}
ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
function getThisParameter(signature) {
- if (signature.parameters.length) {
+ if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
var thisParameter = signature.parameters[0];
if (parameterIsThisKeyword(thisParameter)) {
return thisParameter;
@@ -8322,16 +7320,33 @@ var ts;
}
ts.getTypeAnnotationNode = getTypeAnnotationNode;
function getEffectiveReturnTypeNode(node) {
+ if (ts.isJSDocSignature(node)) {
+ return node.type && node.type.typeExpression && node.type.typeExpression.type;
+ }
return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined);
}
ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
function getEffectiveTypeParameterDeclarations(node) {
- return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined);
+ if (ts.isJSDocSignature(node)) {
+ return ts.emptyArray;
+ }
+ if (isJSDocTypeAlias(node)) {
+ ts.Debug.assert(node.parent.kind === 285);
+ var templateTags = ts.flatMap(ts.filter(node.parent.tags, ts.isJSDocTemplateTag), function (tag) { return tag.typeParameters; });
+ var templateTagNodes = templateTags;
+ templateTagNodes.pos = templateTagNodes.length > 0 ? ts.first(templateTagNodes).pos : node.pos;
+ templateTagNodes.end = templateTagNodes.length > 0 ? ts.last(templateTagNodes).end : node.end;
+ templateTagNodes.hasTrailingComma = false;
+ return templateTagNodes;
+ }
+ return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : ts.emptyArray);
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
- var templateTag = ts.getJSDocTemplateTag(node);
- return templateTag && templateTag.typeParameters;
+ var tag = ts.find(ts.getJSDocTags(node), function (tag) {
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 && tag.parent.tags.some(isJSDocTypeAlias));
+ });
+ return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
function getEffectiveSetAccessorTypeAnnotationNode(node) {
@@ -8956,12 +7971,6 @@ var ts;
return accessKind(node) !== 0;
}
ts.isWriteAccess = isWriteAccess;
- var AccessKind;
- (function (AccessKind) {
- AccessKind[AccessKind["Read"] = 0] = "Read";
- AccessKind[AccessKind["Write"] = 1] = "Write";
- AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
- })(AccessKind || (AccessKind = {}));
function accessKind(node) {
var parent = node.parent;
if (!parent)
@@ -9456,8 +8465,8 @@ var ts;
break;
case 71:
return declaration;
- case 293:
- case 288: {
+ case 297:
+ case 292: {
var name = declaration.name;
if (name.kind === 145) {
return name.right;
@@ -9476,7 +8485,9 @@ var ts;
return undefined;
}
}
- case 292:
+ case 291:
+ return declaration.name;
+ case 296:
return getNameOfJSDocTypedef(declaration);
case 248: {
var expression = declaration.expression;
@@ -9564,7 +8575,9 @@ var ts;
function getJSDocTags(node) {
var tags = node.jsDocCache;
if (tags === undefined) {
- node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; });
+ var comments = ts.getJSDocCommentsAndTags(node);
+ ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
+ node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
}
return tags;
}
@@ -9674,6 +8687,10 @@ var ts;
return node.kind === 159;
}
ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ function isGetOrSetAccessorDeclaration(node) {
+ return node.kind === 156 || node.kind === 155;
+ }
+ ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
function isTypePredicateNode(node) {
return node.kind === 160;
}
@@ -9799,7 +8816,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 296) {
+ while (node.kind === 300) {
node = node.expression;
}
return node;
@@ -10146,85 +9163,93 @@ var ts;
}
ts.isBundle = isBundle;
function isJSDocTypeExpression(node) {
- return node.kind === 275;
+ return node.kind === 277;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 276;
+ return node.kind === 278;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 277;
+ return node.kind === 279;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 278;
+ return node.kind === 280;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 279;
+ return node.kind === 281;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 280;
+ return node.kind === 282;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 281;
+ return node.kind === 283;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 282;
+ return node.kind === 284;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 283;
+ return node.kind === 285;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 286;
+ return node.kind === 289;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 287;
+ return node.kind === 290;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocParameterTag(node) {
- return node.kind === 288;
+ return node.kind === 292;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 289;
+ return node.kind === 293;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 290;
+ return node.kind === 294;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 291;
+ return node.kind === 295;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 292;
+ return node.kind === 296;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 293;
+ return node.kind === 297;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 293 || node.kind === 288;
+ return node.kind === 297 || node.kind === 292;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 284;
+ return node.kind === 286;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
+ function isJSDocCallbackTag(node) {
+ return node.kind === 291;
+ }
+ ts.isJSDocCallbackTag = isJSDocCallbackTag;
+ function isJSDocSignature(node) {
+ return node.kind === 287;
+ }
+ ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
(function (ts) {
function isSyntaxList(n) {
- return n.kind === 294;
+ return n.kind === 298;
}
ts.isSyntaxList = isSyntaxList;
function isNode(node) {
@@ -10346,10 +9371,11 @@ var ts;
switch (kind) {
case 152:
case 157:
+ case 287:
case 158:
case 159:
case 162:
- case 281:
+ case 283:
case 163:
return true;
default:
@@ -10428,13 +9454,13 @@ var ts;
|| kind === 95
|| kind === 131
|| kind === 206
- || kind === 276
- || kind === 277
|| kind === 278
|| kind === 279
|| kind === 280
|| kind === 281
- || kind === 282;
+ || kind === 282
+ || kind === 283
+ || kind === 284;
}
function isTypeNode(node) {
return isTypeNodeKind(node.kind);
@@ -10621,8 +9647,8 @@ var ts;
case 203:
case 207:
case 205:
- case 297:
- case 296:
+ case 301:
+ case 300:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -10635,11 +9661,11 @@ var ts;
}
ts.isAssertionExpression = isAssertionExpression;
function isPartiallyEmittedExpression(node) {
- return node.kind === 296;
+ return node.kind === 300;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
function isNotEmittedStatement(node) {
- return node.kind === 295;
+ return node.kind === 299;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
function isNotEmittedOrPartiallyEmittedNode(node) {
@@ -10739,7 +9765,9 @@ var ts;
|| kind === 236
|| kind === 147
|| kind === 231
- || kind === 292;
+ || kind === 296
+ || kind === 291
+ || kind === 297;
}
function isDeclarationStatementKind(kind) {
return kind === 233
@@ -10774,13 +9802,13 @@ var ts;
|| kind === 213
|| kind === 218
|| kind === 225
- || kind === 295
|| kind === 299
- || kind === 298;
+ || kind === 303
+ || kind === 302;
}
function isDeclaration(node) {
if (node.kind === 147) {
- return node.parent.kind !== 291 || ts.isInJavaScriptFile(node);
+ return node.parent.kind !== 295 || ts.isInJavaScriptFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -10858,15 +9886,15 @@ var ts;
}
ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
function isJSDocNode(node) {
- return node.kind >= 275 && node.kind <= 293;
+ return node.kind >= 277 && node.kind <= 297;
}
ts.isJSDocNode = isJSDocNode;
function isJSDocCommentContainingNode(node) {
- return node.kind === 283 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
+ return node.kind === 285 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
function isJSDocTag(node) {
- return node.kind >= 285 && node.kind <= 293;
+ return node.kind >= 288 && node.kind <= 297;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -10911,12 +9939,12 @@ var ts;
case 231:
case 233:
case 236:
- case 275:
- case 278:
- case 279:
+ case 277:
case 280:
case 281:
case 282:
+ case 283:
+ case 284:
return true;
}
return false;
@@ -12546,11 +11574,10 @@ var ts;
}
}
function scanJSDocToken() {
+ startPos = tokenPos = pos;
if (pos >= end) {
return token = 1;
}
- startPos = pos;
- tokenPos = pos;
var ch = text.charCodeAt(pos);
pos++;
switch (ch) {
@@ -12678,16 +11705,6 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var SignatureFlags;
- (function (SignatureFlags) {
- SignatureFlags[SignatureFlags["None"] = 0] = "None";
- SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
- SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
- SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
- SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList";
- SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
- SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
- })(SignatureFlags || (SignatureFlags = {}));
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
@@ -13077,7 +12094,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 252:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 297:
+ case 301:
return visitNodes(cbNode, cbNodes, node.elements);
case 254:
return visitNode(cbNode, node.openingElement) ||
@@ -13104,23 +12121,23 @@ var ts;
visitNode(cbNode, node.expression);
case 257:
return visitNode(cbNode, node.tagName);
- case 275:
+ case 277:
return visitNode(cbNode, node.type);
- case 279:
- return visitNode(cbNode, node.type);
- case 278:
+ case 281:
return visitNode(cbNode, node.type);
case 280:
return visitNode(cbNode, node.type);
- case 281:
- return visitNodes(cbNode, cbNodes, node.parameters) ||
- visitNode(cbNode, node.type);
case 282:
return visitNode(cbNode, node.type);
case 283:
+ return visitNodes(cbNode, cbNodes, node.parameters) ||
+ visitNode(cbNode, node.type);
+ case 284:
+ return visitNode(cbNode, node.type);
+ case 285:
return visitNodes(cbNode, cbNodes, node.tags);
- case 288:
- case 293:
+ case 292:
+ case 297:
if (node.isNameFirst) {
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression);
@@ -13129,17 +12146,17 @@ var ts;
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
}
+ case 293:
+ return visitNode(cbNode, node.typeExpression);
+ case 294:
+ return visitNode(cbNode, node.typeExpression);
case 289:
- return visitNode(cbNode, node.typeExpression);
- case 290:
- return visitNode(cbNode, node.typeExpression);
- case 286:
return visitNode(cbNode, node.class);
- case 291:
+ case 295:
return visitNodes(cbNode, cbNodes, node.typeParameters);
- case 292:
+ case 296:
if (node.typeExpression &&
- node.typeExpression.kind === 275) {
+ node.typeExpression.kind === 277) {
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName);
}
@@ -13147,7 +12164,16 @@ var ts;
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
}
- case 284:
+ case 291:
+ return visitNode(cbNode, node.fullName) ||
+ visitNode(cbNode, node.typeExpression);
+ case 287:
+ return visitNodes(cbNode, cbNodes, node.decorators) ||
+ visitNodes(cbNode, cbNodes, node.modifiers) ||
+ visitNodes(cbNode, cbNodes, node.typeParameters) ||
+ visitNodes(cbNode, cbNodes, node.parameters) ||
+ visitNode(cbNode, node.type);
+ case 286:
if (node.jsDocPropertyTags) {
for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
var tag = _a[_i];
@@ -13155,7 +12181,7 @@ var ts;
}
}
return;
- case 296:
+ case 300:
return visitNode(cbNode, node.expression);
}
}
@@ -13163,7 +12189,13 @@ var ts;
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
- var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind);
+ var result;
+ if (languageVersion === 100) {
+ result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes);
+ }
+ else {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind);
+ }
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
return result;
@@ -13220,6 +12252,13 @@ var ts;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
scriptKind = ts.ensureScriptKind(fileName, scriptKind);
+ if (scriptKind === 6) {
+ var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
+ ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined);
+ result_1.typeReferenceDirectives = ts.emptyArray;
+ result_1.amdDependencies = ts.emptyArray;
+ return result_1;
+ }
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
clearState();
@@ -13235,23 +12274,54 @@ var ts;
return isInvalid ? entityName : undefined;
}
Parser.parseIsolatedEntityName = parseIsolatedEntityName;
- function parseJsonText(fileName, sourceText) {
- initializeState(sourceText, 2, undefined, 6);
+ function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
+ if (languageVersion === void 0) { languageVersion = 2; }
+ initializeState(sourceText, languageVersion, syntaxCursor, 6);
sourceFile = createSourceFile(fileName, 2, 6, false);
- var result = sourceFile;
nextToken();
+ var pos = getNodePos();
if (token() === 1) {
+ sourceFile.statements = createNodeArray([], pos, pos);
sourceFile.endOfFileToken = parseTokenNode();
}
- else if (token() === 17 ||
- lookAhead(function () { return token() === 9; })) {
- result.jsonObject = parseObjectLiteralExpression();
+ else {
+ var statement = createNode(215);
+ switch (token()) {
+ case 21:
+ statement.expression = parseArrayLiteralExpression();
+ break;
+ case 101:
+ case 86:
+ case 95:
+ statement.expression = parseTokenNode();
+ break;
+ case 38:
+ if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 56; })) {
+ statement.expression = parsePrefixUnaryExpression();
+ }
+ else {
+ statement.expression = parseObjectLiteralExpression();
+ }
+ break;
+ case 8:
+ case 9:
+ if (lookAhead(function () { return nextToken() !== 56; })) {
+ statement.expression = parseLiteralNode();
+ break;
+ }
+ default:
+ statement.expression = parseObjectLiteralExpression();
+ break;
+ }
+ finishNode(statement);
+ sourceFile.statements = createNodeArray([statement], pos);
sourceFile.endOfFileToken = parseExpectedToken(1, ts.Diagnostics.Unexpected_token);
}
- else {
- parseExpected(17);
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
}
sourceFile.parseDiagnostics = parseDiagnostics;
+ var result = sourceFile;
clearState();
return result;
}
@@ -13274,9 +12344,11 @@ var ts;
switch (scriptKind) {
case 1:
case 2:
- case 6:
contextFlags = 65536;
break;
+ case 6:
+ contextFlags = 65536 | 16777216;
+ break;
default:
contextFlags = 0;
break;
@@ -14266,9 +13338,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(276);
+ var result = createNode(278);
if (postFixEquals) {
- return createJSDocPostfixType(280, result);
+ return createJSDocPostfixType(282, result);
}
else {
nextToken();
@@ -14276,7 +13348,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(279);
+ var result = createNode(281);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -14290,18 +13362,18 @@ var ts;
token() === 29 ||
token() === 58 ||
token() === 49) {
- var result = createNode(277, pos);
+ var result = createNode(279, pos);
return finishNode(result);
}
else {
- var result = createNode(278, pos);
+ var result = createNode(280, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(281);
+ var result = createNodeWithJSDoc(283);
nextToken();
fillSignature(56, 4 | 32, result);
return finishNode(result);
@@ -14323,12 +13395,12 @@ var ts;
var dotdotdot = parseOptionalToken(24);
var type = parseType();
if (dotdotdot) {
- var variadic = createNode(282, dotdotdot.pos);
+ var variadic = createNode(284, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 58) {
- return createJSDocPostfixType(280, type);
+ return createJSDocPostfixType(282, type);
}
return type;
}
@@ -14396,10 +13468,11 @@ var ts;
signature.typeParameters = parseTypeParameters();
}
signature.parameters = parseParameterList(flags);
- signature.type = parseReturnType(returnToken, !!(flags & 4));
- }
- function parseReturnType(returnToken, isType) {
- return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined;
+ if (shouldParseReturnType(returnToken, !!(flags & 4))) {
+ signature.type = parseTypeOrTypePredicate();
+ return signature.type !== undefined;
+ }
+ return true;
}
function shouldParseReturnType(returnToken, isType) {
if (returnToken === 36) {
@@ -14621,6 +13694,9 @@ var ts;
var node = createNode(172);
parseExpected(19);
node.type = parseType();
+ if (!node.type) {
+ return undefined;
+ }
parseExpected(20);
return finishNode(node);
}
@@ -14629,7 +13705,12 @@ var ts;
if (kind === 163) {
parseExpected(94);
}
- fillSignature(36, 4, node);
+ if (!fillSignature(36, 4 | (sourceFile.languageVariant === 1 ? 8 : 0), node)) {
+ return undefined;
+ }
+ if (!node.parameters) {
+ return undefined;
+ }
return finishNode(node);
}
function parseKeywordAndNoDot() {
@@ -14782,13 +13863,13 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 51:
- type = createJSDocPostfixType(279, type);
+ type = createJSDocPostfixType(281, type);
break;
case 55:
if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createJSDocPostfixType(278, type);
+ type = createJSDocPostfixType(280, type);
break;
case 21:
parseExpected(21);
@@ -15229,7 +14310,9 @@ var ts;
var node = createNodeWithJSDoc(192);
node.modifiers = parseModifiersForArrowFunction();
var isAsync = ts.hasModifier(node, 256) ? 2 : 0;
- fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node);
+ if (!fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node)) {
+ return undefined;
+ }
if (!node.parameters) {
return undefined;
}
@@ -17115,39 +16198,6 @@ var ts;
function isImportMeta(node) {
return ts.isMetaProperty(node) && node.keywordToken === 91 && node.name.escapedText === "meta";
}
- var ParsingContext;
- (function (ParsingContext) {
- ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
- ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
- ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
- ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
- ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
- ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
- ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
- ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
- ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
- ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
- ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
- ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
- ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
- ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
- ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
- ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
- ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
- ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties";
- ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters";
- ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments";
- ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes";
- ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses";
- ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers";
- ParsingContext[ParsingContext["Count"] = 23] = "Count";
- })(ParsingContext || (ParsingContext = {}));
- var Tristate;
- (function (Tristate) {
- Tristate[Tristate["False"] = 0] = "False";
- Tristate[Tristate["True"] = 1] = "True";
- Tristate[Tristate["Unknown"] = 2] = "Unknown";
- })(Tristate || (Tristate = {}));
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
@@ -17162,7 +16212,7 @@ var ts;
}
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(275, scanner.getTokenPos());
+ var result = createNode(277, scanner.getTokenPos());
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17);
result.type = doInsideOfContext(2097152, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -17182,6 +16232,7 @@ var ts;
}
JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
function parseJSDocComment(parent, start, length) {
+ var _a;
var saveToken = currentToken;
var saveParseDiagnosticsLength = parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
@@ -17199,20 +16250,8 @@ var ts;
parseDiagnostics.length = saveParseDiagnosticsLength;
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
return comment;
- var _a;
}
JSDocParser.parseJSDocComment = parseJSDocComment;
- var JSDocState;
- (function (JSDocState) {
- JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
- JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
- JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
- })(JSDocState || (JSDocState = {}));
- var PropertyLikeParse;
- (function (PropertyLikeParse) {
- PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property";
- PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter";
- })(PropertyLikeParse || (PropertyLikeParse = {}));
function parseJSDocCommentWorker(start, length) {
var content = sourceText;
start = start || 0;
@@ -17254,7 +16293,7 @@ var ts;
case 57:
if (state === 0 || state === 1) {
removeTrailingNewlines(comments);
- parseTag(indent);
+ addTag(parseTag(indent));
state = 0;
margin = undefined;
indent++;
@@ -17318,12 +16357,28 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(283, start);
+ var result = createNode(285, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
}
+ function isNextNonwhitespaceTokenEndOfFile() {
+ while (true) {
+ nextJSDocToken();
+ if (token() === 1) {
+ return true;
+ }
+ if (!(token() === 5 || token() === 4)) {
+ return false;
+ }
+ }
+ }
function skipWhitespace() {
+ if (token() === 5 || token() === 4) {
+ if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
+ return;
+ }
+ }
while (token() === 5 || token() === 4) {
nextJSDocToken();
}
@@ -17352,8 +16407,7 @@ var ts;
case "arg":
case "argument":
case "param":
- addTag(parseParameterOrPropertyTag(atToken, tagName, 1, indent));
- return;
+ return parseParameterOrPropertyTag(atToken, tagName, 2, indent);
case "return":
case "returns":
tag = parseReturnTag(atToken, tagName);
@@ -17365,7 +16419,10 @@ var ts;
tag = parseTypeTag(atToken, tagName);
break;
case "typedef":
- tag = parseTypedefTag(atToken, tagName);
+ tag = parseTypedefTag(atToken, tagName, indent);
+ break;
+ case "callback":
+ tag = parseCallbackTag(atToken, tagName, indent);
break;
default:
tag = parseUnknownTag(atToken, tagName);
@@ -17378,8 +16435,10 @@ var ts;
if (!tag) {
return;
}
- tag.comment = parseTagComments(indent + tag.end - tag.pos);
- addTag(tag);
+ if (!tag.comment) {
+ tag.comment = parseTagComments(indent + tag.end - tag.pos);
+ }
+ return tag;
}
function parseTagComments(indent) {
var comments = [];
@@ -17436,12 +16495,15 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(285, atToken.pos);
+ var result = createNode(288, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
}
function addTag(tag) {
+ if (!tag) {
+ return;
+ }
if (!tags) {
tags = [tag];
tagsPos = tag.pos;
@@ -17490,8 +16552,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 ?
- createNode(288, atToken.pos) :
- createNode(293, atToken.pos);
+ createNode(297, atToken.pos) :
+ createNode(292, atToken.pos);
var comment;
if (indent !== undefined)
comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
@@ -17511,18 +16573,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(275, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(277, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) {
- if (child.kind === 288 || child.kind === 293) {
+ if (child.kind === 292 || child.kind === 297) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(284, start_2);
+ jsdocTypeLiteral = createNode(286, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 166) {
jsdocTypeLiteral.isArrayType = true;
@@ -17533,27 +16595,27 @@ var ts;
}
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 289; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 293; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(289, atToken.pos);
+ var result = createNode(293, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 290; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 294; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(290, atToken.pos);
+ var result = createNode(294, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(true);
return finishNode(result);
}
function parseAugmentsTag(atToken, tagName) {
- var result = createNode(286, atToken.pos);
+ var result = createNode(289, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
@@ -17581,30 +16643,23 @@ var ts;
return node;
}
function parseClassTag(atToken, tagName) {
- var tag = createNode(287, atToken.pos);
+ var tag = createNode(290, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
}
- function parseTypedefTag(atToken, tagName) {
+ function parseTypedefTag(atToken, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(292, atToken.pos);
+ var typedefTag = createNode(296, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
- typedefTag.fullName = parseJSDocTypeNameWithNamespace(0);
- if (typedefTag.fullName) {
- var rightNode = typedefTag.fullName;
- while (true) {
- if (rightNode.kind === 71 || !rightNode.body) {
- typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name;
- break;
- }
- rightNode = rightNode.body;
- }
- }
+ typedefTag.fullName = parseJSDocTypeNameWithNamespace();
+ typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
skipWhitespace();
+ typedefTag.comment = parseTagComments(indent);
typedefTag.typeExpression = typeExpression;
+ var end;
if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
var child = void 0;
var jsdocTypeLiteral = void 0;
@@ -17612,9 +16667,9 @@ var ts;
var start_3 = scanner.getStartPos();
while (child = tryParse(function () { return parseChildPropertyTag(); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(284, start_3);
+ jsdocTypeLiteral = createNode(286, start_3);
}
- if (child.kind === 290) {
+ if (child.kind === 294) {
if (childTypeTag) {
break;
}
@@ -17633,23 +16688,67 @@ var ts;
typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
childTypeTag.typeExpression :
finishNode(jsdocTypeLiteral);
+ end = typedefTag.typeExpression.end;
}
}
- return finishNode(typedefTag);
- function parseJSDocTypeNameWithNamespace(flags) {
- var pos = scanner.getTokenPos();
- var typeNameOrNamespaceName = parseJSDocIdentifierName();
- if (typeNameOrNamespaceName && parseOptional(23)) {
- var jsDocNamespaceNode = createNode(238, pos);
- jsDocNamespaceNode.flags |= flags;
- jsDocNamespaceNode.name = typeNameOrNamespaceName;
- jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4);
- return finishNode(jsDocNamespaceNode);
+ return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
+ }
+ function parseJSDocTypeNameWithNamespace(nested) {
+ var pos = scanner.getTokenPos();
+ var typeNameOrNamespaceName = parseJSDocIdentifierName();
+ if (typeNameOrNamespaceName && parseOptional(23)) {
+ var jsDocNamespaceNode = createNode(238, pos);
+ if (nested) {
+ jsDocNamespaceNode.flags |= 4;
}
- if (typeNameOrNamespaceName && flags & 4) {
- typeNameOrNamespaceName.isInJSDocNamespace = true;
+ jsDocNamespaceNode.name = typeNameOrNamespaceName;
+ jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(true);
+ return finishNode(jsDocNamespaceNode);
+ }
+ if (typeNameOrNamespaceName && nested) {
+ typeNameOrNamespaceName.isInJSDocNamespace = true;
+ }
+ return typeNameOrNamespaceName;
+ }
+ function parseCallbackTag(atToken, tagName, indent) {
+ var callbackTag = createNode(291, atToken.pos);
+ callbackTag.atToken = atToken;
+ callbackTag.tagName = tagName;
+ callbackTag.fullName = parseJSDocTypeNameWithNamespace();
+ callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
+ skipWhitespace();
+ callbackTag.comment = parseTagComments(indent);
+ var child;
+ var start = scanner.getStartPos();
+ var jsdocSignature = createNode(287, start);
+ jsdocSignature.parameters = [];
+ while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) {
+ jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
+ }
+ var returnTag = tryParse(function () {
+ if (token() === 57) {
+ nextJSDocToken();
+ var tag = parseTag(indent);
+ if (tag && tag.kind === 293) {
+ return tag;
+ }
+ }
+ });
+ if (returnTag) {
+ jsdocSignature.type = returnTag;
+ }
+ callbackTag.typeExpression = finishNode(jsdocSignature);
+ return finishNode(callbackTag);
+ }
+ function getJSDocTypeAliasName(fullName) {
+ if (fullName) {
+ var rightNode = fullName;
+ while (true) {
+ if (ts.isIdentifier(rightNode) || !rightNode.body) {
+ return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
+ }
+ rightNode = rightNode.body;
}
- return typeNameOrNamespaceName;
}
}
function escapedTextsEqual(a, b) {
@@ -17665,7 +16764,7 @@ var ts;
return a.escapedText === b.escapedText;
}
function parseChildPropertyTag() {
- return parseChildParameterOrPropertyTag(0);
+ return parseChildParameterOrPropertyTag(1);
}
function parseChildParameterOrPropertyTag(target, name) {
var canParseTag = true;
@@ -17675,7 +16774,8 @@ var ts;
case 57:
if (canParseTag) {
var child = tryParseChildTag(target);
- if (child && child.kind === 288 &&
+ if (child && child.kind === 292 &&
+ target !== 4 &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
}
@@ -17714,20 +16814,20 @@ var ts;
var t;
switch (tagName.escapedText) {
case "type":
- return target === 0 && parseTypeTag(atToken, tagName);
+ return target === 1 && parseTypeTag(atToken, tagName);
case "prop":
case "property":
- t = 0;
+ t = 1;
break;
case "arg":
case "argument":
case "param":
- t = 1;
+ t = 2 | 4;
break;
default:
return false;
}
- if (target !== t) {
+ if (!(target & t)) {
return false;
}
var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined);
@@ -17759,7 +16859,7 @@ var ts;
break;
}
}
- var result = createNode(291, atToken.pos);
+ var result = createNode(295, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -17805,7 +16905,7 @@ var ts;
var pos = scanner.getTokenPos();
var end = scanner.getTextPos();
var result = createNode(71, pos);
- result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end));
+ result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText());
finishNode(result, end);
nextJSDocToken();
return result;
@@ -18101,10 +17201,6 @@ var ts;
}
}
}
- var InvalidPosition;
- (function (InvalidPosition) {
- InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
- })(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
function isDeclarationFileName(fileName) {
return ts.fileExtensionIs(fileName, ".d.ts");
@@ -18536,6 +17632,13 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
+ {
+ name: "composite",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_project_compilation,
+ },
{
name: "removeComments",
type: "boolean",
@@ -18786,6 +17889,12 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "resolveJsonModule",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Include_modules_imported_with_json_extension
+ },
{
name: "listFiles",
type: "boolean",
@@ -19067,11 +18176,13 @@ var ts;
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
+ var projectReferences = undefined;
var errors = [];
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
errors: errors
};
function parseStrings(args) {
@@ -19179,6 +18290,26 @@ var ts;
}
return optionNameMap.get(optionName);
}
+ function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
+ var configFileText;
+ try {
+ configFileText = host.readFile(configFileName);
+ }
+ catch (e) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ if (!configFileText) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ var result = ts.parseJsonText(configFileName, configFileText);
+ var cwd = host.getCurrentDirectory();
+ return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
+ }
+ ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
function readConfigFile(fileName, readFile) {
var textOrDiagnostic = tryReadFile(fileName, readFile);
return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
@@ -19213,69 +18344,84 @@ var ts;
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
if (_tsconfigRootOptions === undefined) {
- _tsconfigRootOptions = commandLineOptionsToMap([
- {
- name: "compilerOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
- },
- {
- name: "typingOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "typeAcquisition",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "extends",
- type: "string"
- },
- {
- name: "files",
- type: "list",
- element: {
+ _tsconfigRootOptions = {
+ name: undefined,
+ type: "object",
+ elementOptions: commandLineOptionsToMap([
+ {
+ name: "compilerOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
+ },
+ {
+ name: "typingOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "typeAcquisition",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "extends",
+ type: "string"
+ },
+ {
+ name: "references",
+ type: "list",
+ element: {
+ name: "references",
+ type: "object"
+ }
+ },
+ {
name: "files",
- type: "string"
- }
- },
- {
- name: "include",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "files",
+ type: "string"
+ }
+ },
+ {
name: "include",
- type: "string"
- }
- },
- {
- name: "exclude",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
+ }
+ },
+ {
name: "exclude",
- type: "string"
- }
- },
- ts.compileOnSaveCommandLineOption
- ]);
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
+ }
+ },
+ ts.compileOnSaveCommandLineOption
+ ])
+ };
}
return _tsconfigRootOptions;
}
function convertToObject(sourceFile, errors) {
- return convertToObjectWorker(sourceFile, errors, undefined, undefined);
+ return convertToObjectWorker(sourceFile, errors, true, undefined, undefined);
}
ts.convertToObject = convertToObject;
- function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) {
- if (!sourceFile.jsonObject) {
- return {};
+ function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
+ if (!sourceFile.statements.length) {
+ return returnValue ? {} : undefined;
+ }
+ return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
+ function isRootOptionMap(knownOptions) {
+ return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
}
- return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined);
function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
- var result = {};
+ var result = returnValue ? {} : undefined;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var element = _a[_i];
if (element.kind !== 269) {
@@ -19295,16 +18441,18 @@ var ts;
}
var value = convertPropertyValueToJson(element.initializer, option);
if (typeof keyText !== "undefined") {
- result[keyText] = value;
+ if (returnValue) {
+ result[keyText] = value;
+ }
if (jsonConversionNotifier &&
- (parentOption || knownOptions === knownRootOptions)) {
+ (parentOption || isRootOptionMap(knownOptions))) {
var isValidOptionValue = isCompilerOptionsValue(option, value);
if (parentOption) {
if (isValidOptionValue) {
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
}
}
- else if (knownOptions === knownRootOptions) {
+ else if (isRootOptionMap(knownOptions)) {
if (isValidOptionValue) {
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
}
@@ -19318,7 +18466,7 @@ var ts;
return result;
}
function convertArrayLiteralExpressionToJson(elements, elementOption) {
- return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); });
}
function convertPropertyValueToJson(valueExpression, option) {
switch (valueExpression.kind) {
@@ -19384,6 +18532,7 @@ var ts;
return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
}
}
+ ts.convertToObjectWorker = convertToObjectWorker;
function getCompilerOptionValueTypeString(option) {
return option.type === "list" ?
"Array" :
@@ -19566,12 +18715,13 @@ var ts;
var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
var raw = parsedConfig.raw;
var options = ts.extend(existingOptions, parsedConfig.options || {});
- options.configFilePath = configFileName;
+ options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
setConfigFileInOptions(options, sourceFile);
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
+ var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences;
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
raw: raw,
errors: errors,
@@ -19610,19 +18760,43 @@ var ts;
createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
}
}
- else {
- var outDir = raw.compilerOptions && raw.compilerOptions.outDir;
- if (outDir) {
- excludeSpecs = [outDir];
+ else if (raw.compilerOptions) {
+ var outDir = raw.compilerOptions.outDir;
+ var declarationDir = raw.compilerOptions.declarationDir;
+ if (outDir || declarationDir) {
+ excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
}
}
if (filesSpecs === undefined && includeSpecs === undefined) {
includeSpecs = ["**/*"];
}
var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) {
+ if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) {
errors.push(getErrorForNoInputFiles(result.spec, configFileName));
}
+ if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
+ if (ts.isArray(raw.references)) {
+ var references = [];
+ for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
+ var ref = _a[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ references.push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
+ }
+ }
+ result.projectReferences = references;
+ }
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
+ }
+ }
return result;
}
function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
@@ -19730,7 +18904,7 @@ var ts;
}
}
};
- var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator);
+ var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator);
if (!typeAcquisition) {
if (typingOptionstypeAcquisition) {
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
@@ -19764,6 +18938,7 @@ var ts;
return extendedConfigPath;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
+ var _a;
var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (sourceFile) {
(sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName);
@@ -19791,7 +18966,6 @@ var ts;
mapPropertiesInRawIfNotUndefined("files");
}
return extendedConfig;
- var _a;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
@@ -19816,7 +18990,7 @@ var ts;
}
ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
function getDefaultCompilerOptions(configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
+ var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
: {};
return options;
@@ -19824,10 +18998,13 @@ var ts;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultCompilerOptions(configFileName);
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
+ if (configFileName) {
+ options.configFilePath = ts.normalizeSlashes(configFileName);
+ }
return options;
}
function getDefaultTypeAcquisition(configFileName) {
- return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
+ return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultTypeAcquisition(configFileName);
@@ -19921,7 +19098,7 @@ var ts;
validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude");
}
var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
- var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
+ var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
}
function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
@@ -19954,8 +19131,12 @@ var ts;
}
var literalFiles = ts.arrayFrom(literalFileMap.values());
var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
+ var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) {
+ return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) });
+ });
return {
fileNames: literalFiles.concat(wildcardFiles),
+ projectReferences: projectReferences,
wildcardDirectories: wildcardDirectories,
spec: spec
};
@@ -19970,20 +19151,10 @@ var ts;
return diag === undefined;
});
function createDiagnostic(message, spec) {
- if (jsonSourceFile && jsonSourceFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) {
- var property = _a[_i];
- if (ts.isArrayLiteralExpression(property.initializer)) {
- for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) {
- var element = _c[_b];
- if (ts.isStringLiteral(element) && element.text === spec) {
- return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec);
- }
- }
- }
- }
- }
- return ts.createCompilerDiagnostic(message, spec);
+ var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
+ return element ?
+ ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
+ ts.createCompilerDiagnostic(message, spec);
}
}
function specToDiagnostic(spec, allowTrailingRecursion) {
@@ -20120,7 +19291,8 @@ var ts;
(function (Extensions) {
Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
- Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly";
+ Extensions[Extensions["Json"] = 2] = "Json";
+ Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly";
})(Extensions || (Extensions = {}));
function resolvedTypeScriptOnly(resolved) {
if (!resolved) {
@@ -20161,7 +19333,13 @@ var ts;
function readJson(path, host) {
try {
var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
}
catch (e) {
return {};
@@ -20571,7 +19749,11 @@ var ts;
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
- var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
+ var result = jsOnly ?
+ tryResolve(Extensions.JavaScript) :
+ (tryResolve(Extensions.TypeScript) ||
+ tryResolve(Extensions.JavaScript) ||
+ (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
if (result && result.value) {
var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations);
@@ -20624,7 +19806,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
- if (!ts.pathEndsWithDirectorySeparator(candidate)) {
+ if (!ts.hasTrailingDirectorySeparator(candidate)) {
if (!onlyRecordFailures) {
var parentOfCandidate = ts.getDirectoryPath(candidate);
if (!directoryProbablyExists(parentOfCandidate, state.host)) {
@@ -20692,6 +19874,10 @@ var ts;
return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state));
}
function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ if (extensions === Extensions.Json) {
+ var extensionLess = ts.tryRemoveExtension(candidate, ".json");
+ return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
+ }
var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
return resolvedByAddingExtension;
@@ -20719,6 +19905,8 @@ var ts;
return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts");
case Extensions.JavaScript:
return tryExtension(".js") || tryExtension(".jsx");
+ case Extensions.Json:
+ return tryExtension(".json");
}
function tryExtension(ext) {
var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
@@ -20770,8 +19958,11 @@ var ts;
}
else {
var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state);
- if (typeof jsPath === "string") {
- subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js"), ".jsx") + ".d.ts";
+ if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) {
+ var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1);
+ subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) {
+ return ts.tryRemoveExtension(potentialSubModule_1, extension);
+ }) || potentialSubModule_1) + ".d.ts";
}
else {
subModuleName = "index.d.ts";
@@ -20803,9 +19994,17 @@ var ts;
}
}
function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) {
- var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state);
+ var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
if (!file) {
- return undefined;
+ if (extensions === Extensions.TypeScript) {
+ file = tryReadPackageJsonFields(false, jsonContent, candidate, state);
+ if (!file) {
+ return undefined;
+ }
+ }
+ else {
+ return undefined;
+ }
}
var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host);
var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state);
@@ -20833,6 +20032,8 @@ var ts;
switch (extensions) {
case Extensions.JavaScript:
return extension === ".js" || extension === ".jsx";
+ case Extensions.Json:
+ return extension === ".json";
case Extensions.TypeScript:
return extension === ".ts" || extension === ".tsx" || extension === ".d.ts";
case Extensions.DtsOnly:
@@ -20898,7 +20099,7 @@ var ts;
if (packageResult) {
return packageResult;
}
- if (extensions !== Extensions.JavaScript) {
+ if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
var nodeModulesAtTypesExists = nodeModulesFolderExists;
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
@@ -21073,12 +20274,42 @@ var ts;
}
JsTyping.isTypingUpToDate = isTypingUpToDate;
JsTyping.nodeCoreModuleList = [
- "buffer", "querystring", "events", "http", "cluster",
- "zlib", "os", "https", "punycode", "repl", "readline",
- "vm", "child_process", "url", "dns", "net",
- "dgram", "fs", "path", "string_decoder", "tls",
- "crypto", "stream", "util", "assert", "tty", "domain",
- "constants", "process", "v8", "timers", "console"
+ "assert",
+ "async_hooks",
+ "buffer",
+ "child_process",
+ "cluster",
+ "console",
+ "constants",
+ "crypto",
+ "dgram",
+ "dns",
+ "domain",
+ "events",
+ "fs",
+ "http",
+ "https",
+ "http2",
+ "inspector",
+ "net",
+ "os",
+ "path",
+ "perf_hooks",
+ "process",
+ "punycode",
+ "querystring",
+ "readline",
+ "repl",
+ "stream",
+ "string_decoder",
+ "timers",
+ "tls",
+ "tty",
+ "url",
+ "util",
+ "v8",
+ "vm",
+ "zlib"
];
JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
function loadSafeList(host, safeListPath) {
@@ -21204,8 +20435,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_1.config;
+ var result_2 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_2.config;
if (baseFileName === "package.json" && packageJson._requiredBy &&
ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
continue;
@@ -21228,16 +20459,6 @@ var ts;
}
}
JsTyping.discoverTypings = discoverTypings;
- var PackageNameValidationResult;
- (function (PackageNameValidationResult) {
- PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok";
- PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported";
- PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName";
- PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong";
- PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot";
- PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore";
- PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters";
- })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {}));
var maxPackageNameLength = 214;
function validatePackageName(packageName) {
if (!packageName) {
@@ -21804,11 +21025,12 @@ var ts;
}());
function getDefaultNPMLocation(processName) {
if (path.basename(processName).indexOf("node") === 0) {
- return "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\"";
- }
- else {
- return "npm";
+ var npmPath = "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\"";
+ if (fs.existsSync(npmPath)) {
+ return npmPath;
+ }
}
+ return "npm";
}
function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
if (!host.fileExists(typesRegistryFilePath)) {
@@ -21984,5 +21206,3 @@ var ts;
})(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-
-//# sourceMappingURL=typingsInstaller.js.map
diff --git a/lib/watchGuard.js b/lib/watchGuard.js
new file mode 100644
index 00000000000..4048f128878
--- /dev/null
+++ b/lib/watchGuard.js
@@ -0,0 +1,27 @@
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */
+
+"use strict";
+if (process.argv.length < 3) {
+ process.exit(1);
+}
+var directoryName = process.argv[2];
+var fs = require("fs");
+try {
+ var watcher = fs.watch(directoryName, { recursive: true }, function () { return ({}); });
+ watcher.close();
+}
+catch (_a) { }
+process.exit(0);
diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json
index 67b76930ca9..b92e4727075 100644
--- a/lib/zh-cn/diagnosticMessages.generated.json
+++ b/lib/zh-cn/diagnosticMessages.generated.json
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "“{0}”的所有声明必须具有相同的修饰符。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "“{0}”的所有声明都必须具有相同的类型参数。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。",
+ "All_destructured_elements_are_unused_6198": "未取消使用任何解构元素。",
"All_imports_in_import_declaration_are_unused_6192": "未使用导入声明中的所有导入。",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。",
"Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "不能调用可能是 \"null\" 的对象。",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "不能调用可能是 \"null\" 或“未定义”的对象。",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "不能调用可能是“未定义”的对象。",
+ "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "无法为项目“{0}”添加前缀,因为它未设置 \"outFile\"",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "提供 \"--isolatedModules\" 标记时无法重新导出类型。",
"Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。",
"Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "编译给定了其配置文件路径或带 \"tsconfig.json\" 的文件夹路径的项目。",
"Compiler_option_0_expects_an_argument_6044": "编译器选项“{0}”需要参数。",
"Compiler_option_0_requires_a_value_of_type_1_5024": "编译器选项“{0}”需要类型 {1} 的值。",
+ "Composite_projects_may_not_disable_declaration_emit_6304": "复合项目可能不会禁用声明发出。",
"Computed_property_names_are_not_allowed_in_enums_1164": "枚举中不允许计算属性名。",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "含字符串值成员的枚举中不允许使用计算值。",
"Concatenate_and_emit_output_to_single_file_6001": "连接输出并将其发出到单个文件。",
@@ -271,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生类的构造函数必须包含 \"super\" 调用。",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。",
"Convert_all_constructor_functions_to_classes_95045": "将所有构造函数都转换为类",
+ "Convert_all_require_to_import_95048": "将所有 \"require\" 转换为 \"import\"",
"Convert_all_to_default_imports_95035": "全部转换为默认导入",
"Convert_function_0_to_class_95002": "将函数“{0}”转换为类",
"Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类",
+ "Convert_require_to_import_95047": "将 \"require\" 转换为 \"import\"",
"Convert_to_ES6_module_95017": "转换为 ES6 模块",
"Convert_to_default_import_95013": "转换为默认导入",
"Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。",
@@ -326,8 +331,8 @@
"Duplicate_label_0_1114": "标签“{0}”重复。",
"Duplicate_number_index_signature_2375": "数字索引签名重复。",
"Duplicate_string_index_signature_2374": "字符串索引签名重复。",
- "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "面向 ECMAScript 2015 模块时,不能使用动态导入。",
"Dynamic_import_cannot_have_type_arguments_1326": "动态导入不能含有类型参数",
+ "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "仅当 \"--module\" 标志为 \"commonjs\" 或 \"esNext\" 时,才支持动态导入。",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "动态导入必须具有一个说明符作为参数。",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "动态导入的说明符类型必须是 \"string\",但此处类型是 \"{0}\"。",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "元素隐式具有 \"any\" 类型,因为索引表达式的类型不为 \"number\"。",
@@ -336,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "发出包含源映射而非包含单独文件的单个文件。",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "在单个文件内发出源以及源映射;需要设置 \"--inlineSourceMap\" 或 \"--sourceMap\"。",
"Enable_all_strict_type_checking_options_6180": "启用所有严格类型检查选项。",
+ "Enable_project_compilation_6302": "启用项目编译",
"Enable_strict_checking_of_function_types_6186": "对函数类型启用严格检查。",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。",
"Enable_strict_null_checks_6113": "启用严格的 NULL 检查。",
@@ -397,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "文件“{0}”的扩展名不受支持,正在跳过。",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "不支持文件“{0}”的扩展名。唯一支持的扩展名为 {1}。",
"File_0_is_not_a_module_2306": "文件“{0}”不是模块。",
+ "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "文件“{0}”不在项目文件列表中。项目必须列出的所有文件,或使用“包含”模式。",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "文件“{0}”不在 \"rootDir\"“{1}”下。\"rootDir\" 应包含所有源文件。",
"File_0_not_found_6053": "找不到文件“{0}”。",
"File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...",
@@ -461,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在环境枚举声明中,成员初始化表达式必须是常数表达式。",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在包含多个声明的枚举中,只有一个声明可以省略其第一个枚举元素的初始化表达式。",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 \"const\" 枚举声明中,成员初始化表达式必须是常数表达式。",
+ "Include_modules_imported_with_json_extension_6197": "包括通过 \".json\" 扩展导入的模块",
"Index_signature_in_type_0_only_permits_reading_2542": "类型“{0}”中的索引签名仅允许读取。",
"Index_signature_is_missing_in_type_0_2329": "类型“{0}”中缺少索引签名。",
"Index_signatures_are_incompatible_2330": "索引签名不兼容。",
@@ -559,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== 模块名“{0}”已成功解析为“{1}”。========",
"Module_resolution_kind_is_not_specified_using_0_6088": "未指定模块解析类型,正在使用“{0}”。",
"Module_resolution_using_rootDirs_has_failed_6111": "使用 \"rootDirs\" 的模块解析失败。",
+ "Move_to_a_new_file_95049": "移动到新的文件",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允许使用多个连续的数字分隔符。",
"Multiple_constructor_implementations_are_not_allowed_2392": "不允许存在多个构造函数实现。",
"NEWLINE_6061": "换行符",
@@ -600,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。",
+ "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。",
"Options_Colon_6027": "选项:",
"Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。",
+ "Output_file_0_from_project_1_does_not_exist_6309": "来自项目“{1}”的输出文件“{0}”不存在",
+ "Output_file_0_has_not_been_built_from_source_file_1_6305": "未从源文件“{1}”生成输出文件“{0}”。",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "重载签名与函数实现不兼容。",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "重载签名必须都是抽象的或都是非抽象的。",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "重载签名必须全部为环境签名或非环境签名。",
@@ -645,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "属于编译一部分的已生成文件的打印名称。",
"Print_the_compiler_s_version_6019": "打印编译器的版本。",
"Print_this_message_6017": "打印此消息。",
+ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "项目引用不能形成环形图。检测到循环: {0}",
+ "Projects_to_reference_6300": "要引用的项目",
"Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。",
"Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "类型“{1}”上不存在属性“{0}”。是否忘记使用 \"await\"?",
@@ -692,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "对具有隐式 \"any\" 类型的表达式和声明引发错误。",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。",
"Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。",
+ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "引用的项目“{0}”必须拥有设置 \"composite\": true。",
+ "Remove_all_unreachable_code_95051": "删除所有无法访问的代码",
"Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明",
+ "Remove_destructuring_90009": "删除解构",
"Remove_import_from_0_90005": "从“{0}”删除导入",
+ "Remove_unreachable_code_95050": "删除无法访问的代码",
"Replace_import_with_0_95015": "用“{0}”替换导入。",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "报告 switch 语句中遇到 fallthrough 情况的错误。",
@@ -801,6 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "配置文件“{0}”中的 \"files\" 列表为空。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "承诺的 \"then\" 方法的第一个参数必须是回调。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全局类型 \"JSX.{0}\" 不可具有多个属性。",
+ "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "\"import.meta\" 元属性仅允许对 \"target\" 和 \"module\" 编译器选项使用 \"ESNext\"。",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "\"for...in\" 语句的左侧不能为析构模式。",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "\"for...in\" 语句的左侧不能使用类型批注。",
@@ -1013,6 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" 只能在 .ts 文件中使用。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "指定了 \"paths“ 选项,正在查找模式以匹配模块名“{0}”。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 修饰符仅可出现在属性声明或索引签名中。",
+ "require_call_may_be_converted_to_an_import_80005": "可将“要求”调用转换为导入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "设置了 \"rootDirs\" 选项,可将其用于解析相对模块名称“{0}”。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只能在派生类中引用 \"super\"。",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "仅可在派生类或对象文字表达式的成员中引用 \"super\"。",
diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json
index aa2d1eac0eb..f250984e6f2 100644
--- a/lib/zh-tw/diagnosticMessages.generated.json
+++ b/lib/zh-tw/diagnosticMessages.generated.json
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。",
+ "All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。",
"All_imports_in_import_declaration_are_unused_6192": "匯入宣告中的所有匯入皆未使用。",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。",
"Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "無法叫用可能為 'null' 的物件。",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "無法叫用可能為 'null' 或 'undefined' 的物件。",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "無法叫用可能為 'undefined' 的物件。",
+ "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "因為專案 '{0}' 未設定 'outFile',所以無法於其前面加上任何內容",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "如有提供 '--isolatedModules' 旗標,即無法重新匯出類型。",
"Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。",
"Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "當路徑為專案組態檔或為 'tsconfig.json' 所在的資料夾時編譯專案。",
"Compiler_option_0_expects_an_argument_6044": "編譯器選項 '{0}' 必須要有一個引數。",
"Compiler_option_0_requires_a_value_of_type_1_5024": "編譯器選項 '{0}' 需要類型 {1} 的值。",
+ "Composite_projects_may_not_disable_declaration_emit_6304": "複合式專案可能未停用宣告發出。",
"Computed_property_names_are_not_allowed_in_enums_1164": "列舉中不能有計算的屬性名稱。",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "具有字串值成員的列舉中不允許計算值。",
"Concatenate_and_emit_output_to_single_file_6001": "串連並發出輸出至單一檔案。",
@@ -271,11 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "衍生類別的建構函式必須包含 'super' 呼叫。",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。",
"Convert_all_constructor_functions_to_classes_95045": "將所有建構函式轉換為類別",
- "Convert_all_require_to_import_95048": "Convert all 'require' to 'import'",
+ "Convert_all_require_to_import_95048": "將所有 'require' 轉換至 'import'",
"Convert_all_to_default_imports_95035": "全部轉換為預設匯入",
"Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別",
"Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別",
- "Convert_require_to_import_95047": "Convert 'require' to 'import'",
+ "Convert_require_to_import_95047": "將 'require' 轉換至 'import'",
"Convert_to_ES6_module_95017": "轉換為 ES6 模組",
"Convert_to_default_import_95013": "轉換為預設匯入",
"Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。",
@@ -328,8 +331,8 @@
"Duplicate_label_0_1114": "標籤 '{0}' 重複。",
"Duplicate_number_index_signature_2375": "數字索引簽章重複。",
"Duplicate_string_index_signature_2374": "字串索引簽章重複。",
- "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "以 ECMAScript 2015 模組為目標時,無法使用動態匯入。",
"Dynamic_import_cannot_have_type_arguments_1326": "動態匯入不能有型別引數",
+ "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "只有當 '--module' 旗標是 'commonjs' 或 'esNext' 時,才支援動態匯入。",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動態匯入必須有一個指定名稱作為引數。",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動態匯入的指定名稱必須屬於類型 'string',但這裡的類型為 '{0}'。",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "因為索引運算式不屬於類型 'number',所以元素具有隱含 'any' 類型。",
@@ -338,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "發出單一檔案包含來源對應,而不要使用個別的檔案。",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "使用單一檔案發出來源與來源對應。必須設定 '--inlineSourceMap' 或 '--sourceMap'。",
"Enable_all_strict_type_checking_options_6180": "啟用所有 Strict 類型檢查選項。",
+ "Enable_project_compilation_6302": "啟用專案編譯",
"Enable_strict_checking_of_function_types_6186": "啟用嚴格檢查函式類型。",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。",
"Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。",
@@ -399,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "因為不支援檔案 '{0}' 的副檔名,所以將其跳過。",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "檔案 '{0}' 的附檔名不受支援。僅支援副檔名 {1}。",
"File_0_is_not_a_module_2306": "檔案 '{0}' 不是模組。",
+ "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "檔案 '{0}' 不在專案檔案清單內。專案必須列出所有檔案,或使用 'include' 模式。",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "檔案 '{0}' 不在 'rootDir' '{1}' 之下。'rootDir' 必須包含所有原始程式檔。",
"File_0_not_found_6053": "找不到檔案 '{0}'。",
"File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...",
@@ -463,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在環境列舉宣告中,成員初始設定式必須是常數運算式。",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在具有多個宣告的列舉中,只有一個宣告可以在其第一個列舉項目中省略初始設定式。",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 'const' 列舉宣告中,成員初始設定式必須是常數運算式。",
+ "Include_modules_imported_with_json_extension_6197": "包含匯入有 '.json' 延伸模組的模組",
"Index_signature_in_type_0_only_permits_reading_2542": "類型 '{0}' 中的索引簽章只允許讀取。",
"Index_signature_is_missing_in_type_0_2329": "類型 '{0}' 中遺漏索引簽章。",
"Index_signatures_are_incompatible_2330": "索引簽章不相容。",
@@ -561,6 +567,7 @@
"Module_name_0_was_successfully_resolved_to_1_6089": "======== 模組名稱 '{0}' 已成功解析為 '{1}'。========",
"Module_resolution_kind_is_not_specified_using_0_6088": "未指定模組解析種類,將使用 '{0}'。",
"Module_resolution_using_rootDirs_has_failed_6111": "使用 'rootDirs' 解析模組失敗。",
+ "Move_to_a_new_file_95049": "移至新行",
"Multiple_consecutive_numeric_separators_are_not_permitted_6189": "不允許多個連續的數字分隔符號。",
"Multiple_constructor_implementations_are_not_allowed_2392": "不允許多個建構函式實作。",
"NEWLINE_6061": "新行",
@@ -602,8 +609,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "只有在提供選項 '--module' 或是 'target' 為 'ES2015' 或更高項目時,才可使用選項 'isolatedModules'。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "必須指定 '--baseUrl' 選項才能使用選項 'paths'。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "在命令列上,'project' 選項不得與原始程式檔並用。",
+ "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "指定選項 '-resolveJsonModule' 時,不可沒有 'node' 模組解析策略。",
"Options_Colon_6027": "選項:",
"Output_directory_for_generated_declaration_files_6166": "所產生之宣告檔案的輸出目錄。",
+ "Output_file_0_from_project_1_does_not_exist_6309": "沒有來自專案 '{1}' 的輸出檔 '{0}'",
+ "Output_file_0_has_not_been_built_from_source_file_1_6305": "輸出檔 '{0}' 並非從原始程式檔 '{1}' 建置。",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "多載簽章與函式實作不相容。",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "多載簽章必須全為抽象或非抽象。",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "多載簽章都必須是環境或非環境簽章。",
@@ -647,6 +657,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。",
"Print_the_compiler_s_version_6019": "列印編譯器的版本。",
"Print_this_message_6017": "列印這則訊息。",
+ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "專案參考不會形成循環圖。但偵測到循環: {0}",
+ "Projects_to_reference_6300": "專案至參考",
"Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。",
"Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "類型 '{1}' 不存在屬性 '{0}'。是否忘記要使用 'await'?",
@@ -694,8 +706,12 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "當運算式及宣告包含隱含的 'any' 類型時顯示錯誤。",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。",
"Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。",
+ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "參考的專案 '{0}' 之設定 \"composite\" 必須為 true。",
+ "Remove_all_unreachable_code_95051": "移除所有無法連線的程式碼",
"Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告",
+ "Remove_destructuring_90009": "移除解構",
"Remove_import_from_0_90005": "從 '{0}' 移除匯入",
+ "Remove_unreachable_code_95050": "移除無法連線的程式碼",
"Replace_import_with_0_95015": "以 '{0}' 取代匯入。",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "回報 switch 陳述式內 fallthrough 案例的錯誤。",
@@ -803,7 +819,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "設定檔 '{0}' 中的 'files' 清單是空的。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise 的 'then' 方法第一個參數必須為回撥。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全域類型 'JSX.{0}' 的屬性不得超過一個。",
- "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.",
+ "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "只有在為 'target' 及 'module' 編譯器選項使用 'ESNext' 時,才允許 'import.meta' 中繼屬性。",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 陳述式的左側不得為解構模式。",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 陳述式左側不得使用類型註釋。",
@@ -1016,7 +1032,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾詞只能出現在屬性宣告或索引簽章。",
- "require_call_may_be_converted_to_an_import_80005": "'require' call may be converted to an import.",
+ "require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "只有在衍生類別或物件常值運算式的成員中才可參考 'super'。",