diff --git a/lib/tsc.js b/lib/tsc.js index 46ebb65eec9..2e0c0282eac 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -174,7 +174,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.9"; - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -2124,6 +2124,23 @@ var ts; return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function tryRemoveDirectoryPrefix(path, dirPath) { + var a = tryRemovePrefix(path, dirPath); + if (a === undefined) + return undefined; + switch (a.charCodeAt(0)) { + case 47: + case 92: + return a.slice(1); + default: + return undefined; + } + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -2133,6 +2150,10 @@ var ts; return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; } ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; function stringContains(str, substring) { return str.indexOf(substring) !== -1; } @@ -2272,14 +2293,17 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; @@ -6924,11 +6948,6 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -7319,7 +7338,7 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { + return objectLiteral.properties.filter(function (property) { if (property.kind === 269) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); @@ -7335,15 +7354,18 @@ var ts; } 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; - }); + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, 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 getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -12286,6 +12308,7 @@ var ts; if (languageVersion === void 0) { languageVersion = 2; } initializeState(sourceText, languageVersion, syntaxCursor, 6); sourceFile = createSourceFile(fileName, 2, 6, false); + sourceFile.flags = contextFlags; nextToken(); var pos = getNodePos(); if (token() === 1) { @@ -12666,8 +12689,8 @@ var ts; kind === 71 ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2) { addJSDocComment(node); } @@ -13334,6 +13357,21 @@ var ts; } return finishNode(node); } + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 161: + return ts.nodeIsMissing(node.typeName); + case 162: + case 163: { + var _a = node, parameters = _a.parameters, type = _a.type; + return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type); + } + case 172: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); var node = createNode(160, lhs.pos); @@ -13476,12 +13514,13 @@ var ts; if (!(flags & 32)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + var parametersParsedSuccessfully = parseParameterList(signature, flags); if (shouldParseReturnType(returnToken, !!(flags & 4))) { signature.type = parseTypeOrTypePredicate(); - return signature.type !== undefined; + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; } - return true; + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36) { @@ -13498,21 +13537,19 @@ var ts; } return false; } - function parseParameterList(flags) { - if (parseExpected(19)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1)); - setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20) && (flags & 8)) { - return undefined; - } - return result; + function parseParameterList(signature, flags) { + if (!parseExpected(19)) { + signature.parameters = createMissingList(); + return false; } - return (flags & 8) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + signature.parameters = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20); } function parseTypeMemberSemicolon() { if (parseOptional(26)) { @@ -13703,23 +13740,14 @@ var ts; var node = createNode(172); parseExpected(19); node.type = parseType(); - if (!node.type) { - return undefined; - } parseExpected(20); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163) { - parseExpected(94); - } - if (!fillSignature(36, 4 | (sourceFile.languageVariant === 1 ? 8 : 0), node)) { - return undefined; - } - if (!node.parameters) { - return undefined; - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94) ? 163 : 162; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(36, 4, node); return finishNode(node); } function parseKeywordAndNoDot() { @@ -14018,11 +14046,8 @@ var ts; return doOutsideOfContext(20480, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162); - } - if (token() === 94) { - return parseFunctionOrConstructorType(163); + if (isStartOfFunctionType() || token() === 94) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85)) { @@ -14319,10 +14344,7 @@ var ts; var node = createNodeWithJSDoc(192); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - if (!fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node)) { - return undefined; - } - if (!node.parameters) { + if (!fillSignature(56, isAsync, node) && !allowAmbiguity) { return undefined; } if (!allowAmbiguity && token() !== 36 && token() !== 17) { @@ -20167,6 +20189,8 @@ var ts; } break; case 224: + transformFlags |= 33554432 | 8; + break; case 222: case 223: transformFlags |= 33554432; @@ -22355,7 +22379,12 @@ var ts; } } if (name !== "default" && (result = lookup(moduleExports, name, meaning & 2623475))) { - break loop; + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } } break; case 237: @@ -22451,9 +22480,8 @@ var ts; break; case 296: case 291: - lastLocation = location; - location = ts.getJSDocHost(location).parent; - continue; + location = ts.getJSDocHost(location); + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -22711,7 +22739,7 @@ var ts; : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } function isSyntacticDefault(node) { - return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512)); + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512) || ts.isExportSpecifier(node)); } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { @@ -23297,6 +23325,38 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getContainerOfSymbol(symbol) { + var container = getParentOfSymbol(symbol); + if (container) { + return container; + } + var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!candidate) { + return undefined; + } + var alias = getAliasForSymbolInContainer(candidate, symbol); + return alias ? candidate : undefined; + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576) !== 0 ? getMergedSymbol(symbol.exportSymbol) @@ -23524,7 +23584,7 @@ var ts; } } meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); + symbol = getContainerOfSymbol(symbol); } var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { @@ -24121,9 +24181,12 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319); - if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); + } } } var propertyName = symbolToName(propertySymbol, context, 67216319, true); @@ -24293,12 +24356,12 @@ var ts; var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); if (parent) { var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); if (parentChain) { parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); } } } @@ -28679,12 +28742,13 @@ var ts; return links.resolvedType; } function resolveImportSymbolType(node, links, symbol, meaning) { - links.resolvedSymbol = symbol; + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; if (meaning === 67216319) { return links.resolvedType = getTypeOfSymbol(symbol); } else { - return links.resolvedType = getTypeReferenceType(node, symbol); + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); } } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { @@ -35328,7 +35392,7 @@ var ts; } if (node.kind === 188) { argCount = args.length; - typeArguments = undefined; + typeArguments = node.typeArguments; if (node.template.kind === 201) { var lastSpan = ts.lastOrUndefined(node.template.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -35890,6 +35954,7 @@ var ts; if (node.expression.kind === 97) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { + ts.forEach(node.arguments, checkExpresionNoReturn); return anySignature; } if (superType !== unknownType) { @@ -37551,6 +37616,9 @@ var ts; node.contextualType = saveContextualType; return type; } + function checkExpresionNoReturn(node) { + checkExpression(node); + } function checkExpression(node, checkMode) { var type; if (node.kind === 145) { @@ -38981,7 +39049,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; 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, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); + addDiagnostic(0, ts.createDiagnosticForNode(node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -48033,7 +48101,7 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; @@ -48989,7 +49057,8 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && - !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { @@ -49612,6 +49681,7 @@ var ts; case 165: case 119: case 173: + case 178: break; default: return ts.Debug.failBadSyntaxKind(node); @@ -50864,6 +50934,8 @@ var ts; return visitAwaitExpression(node); case 202: return visitYieldExpression(node); + case 224: + return visitReturnStatement(node); case 227: return visitLabeledStatement(node); case 183: @@ -50922,6 +50994,12 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2) { var statement = ts.unwrapInnermostStatementOfLabel(node); @@ -51071,7 +51149,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), ts.createVariableDeclaration(result) - ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, createDownlevelAwait(getValue))), node), 256); + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, getValue)), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -52648,21 +52726,19 @@ var ts; var singleLine = false; var statementsLocation; var closeBraceLocation; + var leadingStatements = []; var statements = []; var body = node.body; var statementOffset; resumeLexicalEnvironment(); if (ts.isBlock(body)) { - statementOffset = ts.addStandardPrologue(statements, body.statements, false); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, false); - if (!multiLine && statements.length > 0) { - multiLine = true; + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, false); } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, false); if (ts.isBlock(body)) { - statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); if (!multiLine && body.multiLine) { @@ -52692,10 +52768,10 @@ var ts; var lexicalEnvironment = context.endLexicalEnvironment(); ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); - if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1); @@ -55488,7 +55564,7 @@ var ts; name: "typescript:generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); var ts; @@ -58964,7 +59040,7 @@ var ts; return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); } function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled) { + if (disabled || ts.fileExtensionIs(filePath, ".json")) { return; } if (sourceMapData) { @@ -59055,7 +59131,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos)) { + if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { return; } if (extendedDiagnostics) { @@ -59092,7 +59168,7 @@ var ts; } } function emitNodeWithSourceMap(hint, node, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { @@ -59133,7 +59209,7 @@ var ts; } } function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; @@ -59151,12 +59227,18 @@ var ts; } return tokenPos; } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json"); + } function setSourceFile(sourceFile) { if (disabled) { return; } currentSource = sourceFile; currentSourceText = currentSource.text; + if (isJsonSourceMapSource(sourceFile)) { + return; + } var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); @@ -59170,7 +59252,7 @@ var ts; } } function getText() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } encodeLastRecordedSourceMapSpan(); @@ -59185,7 +59267,7 @@ var ts; }); } function getSourceMappingURL() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } if (compilerOptions.inlineSourceMap) { @@ -59597,7 +59679,7 @@ var ts; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; @@ -60734,7 +60816,7 @@ var ts; increaseIndent(); } var preferNewLine = node.multiLine ? 32768 : 0; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 && !ts.isJsonSourceFile(currentSourceFile) ? 32 : 0; emitList(node, node.properties, 263122 | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); @@ -64120,11 +64202,9 @@ var ts; else if (ts.isLiteralImportTypeNode(node)) { imports = ts.append(imports, node.argument.literal); } - else { - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); - } + collectDynamicImportOrRequireCallsForEachChild(node); + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); } } function collectDynamicImportOrRequireCallsForEachChild(node) { @@ -65609,8 +65689,20 @@ var ts; function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } - function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { - for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + return false; + } + if (dirPath.charCodeAt(0) !== 47 && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; if (searchIndex === 0) { return false; @@ -65618,9 +65710,6 @@ var ts; } return true; } - function canWatchDirectory(dirPath) { - return isDirectoryAtleastAtLevelFromFSRoot(dirPath, dirPath.charCodeAt(0) === 47 ? 3 : 1); - } function filterFSRootDirectoriesToWatch(watchPath, dirPath) { if (!canWatchDirectory(dirPath)) { watchPath.ignore = true; @@ -67422,6 +67511,7 @@ var ts; } return optionNameMap.get(optionName); } + ts.getOptionFromName = getOptionFromName; function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { var configFileText; try { diff --git a/lib/tsserver.js b/lib/tsserver.js index 92c48d26447..c5ad1c8d993 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1387,7 +1387,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.9"; - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -3337,6 +3337,23 @@ var ts; return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function tryRemoveDirectoryPrefix(path, dirPath) { + var a = tryRemovePrefix(path, dirPath); + if (a === undefined) + return undefined; + switch (a.charCodeAt(0)) { + case 47: + case 92: + return a.slice(1); + default: + return undefined; + } + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3346,6 +3363,10 @@ var ts; return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; } ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; function stringContains(str, substring) { return str.indexOf(substring) !== -1; } @@ -3485,14 +3506,17 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; @@ -8156,11 +8180,6 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -8551,7 +8570,7 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { + return objectLiteral.properties.filter(function (property) { if (property.kind === 269) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); @@ -8567,15 +8586,18 @@ var ts; } 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; - }); + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, 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 getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -12976,7 +12998,6 @@ var ts; 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 = {})); @@ -13553,6 +13574,7 @@ var ts; if (languageVersion === void 0) { languageVersion = 2; } initializeState(sourceText, languageVersion, syntaxCursor, 6); sourceFile = createSourceFile(fileName, 2, 6, false); + sourceFile.flags = contextFlags; nextToken(); var pos = getNodePos(); if (token() === 1) { @@ -13933,8 +13955,8 @@ var ts; kind === 71 ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2) { addJSDocComment(node); } @@ -14601,6 +14623,21 @@ var ts; } return finishNode(node); } + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 161: + return ts.nodeIsMissing(node.typeName); + case 162: + case 163: { + var _a = node, parameters = _a.parameters, type = _a.type; + return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type); + } + case 172: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); var node = createNode(160, lhs.pos); @@ -14743,12 +14780,13 @@ var ts; if (!(flags & 32)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + var parametersParsedSuccessfully = parseParameterList(signature, flags); if (shouldParseReturnType(returnToken, !!(flags & 4))) { signature.type = parseTypeOrTypePredicate(); - return signature.type !== undefined; + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; } - return true; + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36) { @@ -14765,21 +14803,19 @@ var ts; } return false; } - function parseParameterList(flags) { - if (parseExpected(19)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1)); - setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20) && (flags & 8)) { - return undefined; - } - return result; + function parseParameterList(signature, flags) { + if (!parseExpected(19)) { + signature.parameters = createMissingList(); + return false; } - return (flags & 8) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + signature.parameters = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20); } function parseTypeMemberSemicolon() { if (parseOptional(26)) { @@ -14970,23 +15006,14 @@ var ts; var node = createNode(172); parseExpected(19); node.type = parseType(); - if (!node.type) { - return undefined; - } parseExpected(20); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163) { - parseExpected(94); - } - if (!fillSignature(36, 4 | (sourceFile.languageVariant === 1 ? 8 : 0), node)) { - return undefined; - } - if (!node.parameters) { - return undefined; - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94) ? 163 : 162; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(36, 4, node); return finishNode(node); } function parseKeywordAndNoDot() { @@ -15285,11 +15312,8 @@ var ts; return doOutsideOfContext(20480, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162); - } - if (token() === 94) { - return parseFunctionOrConstructorType(163); + if (isStartOfFunctionType() || token() === 94) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85)) { @@ -15586,10 +15610,7 @@ var ts; var node = createNodeWithJSDoc(192); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - if (!fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node)) { - return undefined; - } - if (!node.parameters) { + if (!fillSignature(56, isAsync, node) && !allowAmbiguity) { return undefined; } if (!allowAmbiguity && token() !== 36 && token() !== 17) { @@ -21506,6 +21527,8 @@ var ts; } break; case 224: + transformFlags |= 33554432 | 8; + break; case 222: case 223: transformFlags |= 33554432; @@ -23798,7 +23821,12 @@ var ts; } } if (name !== "default" && (result = lookup(moduleExports, name, meaning & 2623475))) { - break loop; + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } } break; case 237: @@ -23894,9 +23922,8 @@ var ts; break; case 296: case 291: - lastLocation = location; - location = ts.getJSDocHost(location).parent; - continue; + location = ts.getJSDocHost(location); + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -24154,7 +24181,7 @@ var ts; : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } function isSyntacticDefault(node) { - return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512)); + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512) || ts.isExportSpecifier(node)); } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { @@ -24740,6 +24767,38 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + function getContainerOfSymbol(symbol) { + var container = getParentOfSymbol(symbol); + if (container) { + return container; + } + var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!candidate) { + return undefined; + } + var alias = getAliasForSymbolInContainer(candidate, symbol); + return alias ? candidate : undefined; + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576) !== 0 ? getMergedSymbol(symbol.exportSymbol) @@ -24967,7 +25026,7 @@ var ts; } } meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); + symbol = getContainerOfSymbol(symbol); } var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { @@ -25564,9 +25623,12 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319); - if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); + } } } var propertyName = symbolToName(propertySymbol, context, 67216319, true); @@ -25736,12 +25798,12 @@ var ts; var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); if (parent) { var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); if (parentChain) { parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); } } } @@ -30122,12 +30184,13 @@ var ts; return links.resolvedType; } function resolveImportSymbolType(node, links, symbol, meaning) { - links.resolvedSymbol = symbol; + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; if (meaning === 67216319) { return links.resolvedType = getTypeOfSymbol(symbol); } else { - return links.resolvedType = getTypeReferenceType(node, symbol); + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); } } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { @@ -36771,7 +36834,7 @@ var ts; } if (node.kind === 188) { argCount = args.length; - typeArguments = undefined; + typeArguments = node.typeArguments; if (node.template.kind === 201) { var lastSpan = ts.lastOrUndefined(node.template.templateSpans); ts.Debug.assert(lastSpan !== undefined); @@ -37333,6 +37396,7 @@ var ts; if (node.expression.kind === 97) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { + ts.forEach(node.arguments, checkExpresionNoReturn); return anySignature; } if (superType !== unknownType) { @@ -38994,6 +39058,9 @@ var ts; node.contextualType = saveContextualType; return type; } + function checkExpresionNoReturn(node) { + checkExpression(node); + } function checkExpression(node, checkMode) { var type; if (node.kind === 145) { @@ -40438,7 +40505,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; 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, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name)); + addDiagnostic(0, ts.createDiagnosticForNode(node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -49504,7 +49571,7 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; @@ -50487,7 +50554,8 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && - !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { @@ -51110,6 +51178,7 @@ var ts; case 165: case 119: case 173: + case 178: break; default: return ts.Debug.failBadSyntaxKind(node); @@ -52370,6 +52439,8 @@ var ts; return visitAwaitExpression(node); case 202: return visitYieldExpression(node); + case 224: + return visitReturnStatement(node); case 227: return visitLabeledStatement(node); case 183: @@ -52428,6 +52499,12 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2) { var statement = ts.unwrapInnermostStatementOfLabel(node); @@ -52577,7 +52654,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), ts.createVariableDeclaration(result) - ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, createDownlevelAwait(getValue))), node), 256); + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, getValue)), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -54223,21 +54300,19 @@ var ts; var singleLine = false; var statementsLocation; var closeBraceLocation; + var leadingStatements = []; var statements = []; var body = node.body; var statementOffset; resumeLexicalEnvironment(); if (ts.isBlock(body)) { - statementOffset = ts.addStandardPrologue(statements, body.statements, false); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, false); - if (!multiLine && statements.length > 0) { - multiLine = true; + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, false); } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, false); if (ts.isBlock(body)) { - statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); if (!multiLine && body.multiLine) { @@ -54267,10 +54342,10 @@ var ts; var lexicalEnvironment = context.endLexicalEnvironment(); ts.prependStatements(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, false); - if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1); @@ -57108,7 +57183,7 @@ var ts; name: "typescript:generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); var ts; @@ -60596,7 +60671,7 @@ var ts; return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); } function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled) { + if (disabled || ts.fileExtensionIs(filePath, ".json")) { return; } if (sourceMapData) { @@ -60687,7 +60762,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos)) { + if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { return; } if (extendedDiagnostics) { @@ -60724,7 +60799,7 @@ var ts; } } function emitNodeWithSourceMap(hint, node, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { @@ -60765,7 +60840,7 @@ var ts; } } function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; @@ -60783,12 +60858,18 @@ var ts; } return tokenPos; } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json"); + } function setSourceFile(sourceFile) { if (disabled) { return; } currentSource = sourceFile; currentSourceText = currentSource.text; + if (isJsonSourceMapSource(sourceFile)) { + return; + } var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); @@ -60802,7 +60883,7 @@ var ts; } } function getText() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } encodeLastRecordedSourceMapSpan(); @@ -60817,7 +60898,7 @@ var ts; }); } function getSourceMappingURL() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } if (compilerOptions.inlineSourceMap) { @@ -61229,7 +61310,7 @@ var ts; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; @@ -62373,7 +62454,7 @@ var ts; increaseIndent(); } var preferNewLine = node.multiLine ? 32768 : 0; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 && !ts.isJsonSourceFile(currentSourceFile) ? 32 : 0; emitList(node, node.properties, 263122 | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); @@ -65770,11 +65851,9 @@ var ts; else if (ts.isLiteralImportTypeNode(node)) { imports = ts.append(imports, node.argument.literal); } - else { - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); - } + collectDynamicImportOrRequireCallsForEachChild(node); + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); } } function collectDynamicImportOrRequireCallsForEachChild(node) { @@ -67259,8 +67338,20 @@ var ts; function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } - function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { - for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + return false; + } + if (dirPath.charCodeAt(0) !== 47 && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; if (searchIndex === 0) { return false; @@ -67268,9 +67359,6 @@ var ts; } return true; } - function canWatchDirectory(dirPath) { - return isDirectoryAtleastAtLevelFromFSRoot(dirPath, dirPath.charCodeAt(0) === 47 ? 3 : 1); - } function filterFSRootDirectoriesToWatch(watchPath, dirPath) { if (!canWatchDirectory(dirPath)) { watchPath.ignore = true; @@ -67706,11 +67794,11 @@ 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]; } + var _a; return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, @@ -69072,6 +69160,7 @@ var ts; } return optionNameMap.get(optionName); } + ts.getOptionFromName = getOptionFromName; function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { var configFileText; try { @@ -71262,16 +71351,35 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { return ts.createImportDeclaration(undefined, undefined, defaultImport || namedImports ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) - : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier, preferences.quotePreference === "single") : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); } ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 : 1; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile) ? 0 : 1; + } + } + ts.getQuotePreference = getQuotePreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -71598,9 +71706,9 @@ var ts; function getFirstChild(node) { return node.forEachChild(function (child) { return child; }); } - function getUniqueName(baseName, fileText) { + function getUniqueName(baseName, sourceFile) { var nameText = baseName; - for (var i = 1; ts.stringContains(fileText, nameText); i++) { + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { nameText = baseName + "_" + i; } return nameText; @@ -71615,7 +71723,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = newText.indexOf(name); + var index = indexInTextChange(newText, name); if (index !== -1) { lastPos = span.start + delta + index; if (!preferLastLocation) { @@ -71630,6 +71738,16 @@ var ts; return lastPos; } ts.getRenameLocation = getRenameLocation; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -73158,7 +73276,7 @@ var ts; return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; - var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -75841,19 +75959,28 @@ var ts; return exposedByParent ? scope.getSourceFile() : scope; } function isSymbolReferencedInFile(definition, checker, sourceFile) { - var symbol = checker.getSymbolAtLocation(definition); - if (!symbol) - return true; - return getPossibleSymbolReferenceNodes(sourceFile, symbol.name).some(function (token) { - if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) - return false; - var referenceSymbol = checker.getSymbolAtLocation(token); - return referenceSymbol === symbol - || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol - || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol; - }); + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos, true); }); @@ -76442,64 +76569,176 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - 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) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } + updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); }); } ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var canonicalPath = getCanonicalFileName(path); + if (canonicalPath === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(canonicalPath, canonicalOldPath); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + }; + } + function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, [], includes, useCaseSensitiveFileNames, currentDirectory); + if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, !useCaseSensitiveFileNames); } } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var result = []; + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + var _loop_14 = function (sourceFile) { + var newImportFromPath = oldToNew(sourceFile.fileName) || sourceFile.fileName; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var toImport = oldFromNew !== undefined + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) + : getSourceFileToImport(importLiteral, sourceFile, program, host, oldToNew); + return toImport === undefined ? undefined : ts.moduleSpecifiers.getModuleSpecifier(program, sourceFile, newImportFromPath, toImport, host, preferences); + }); + }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } + _loop_14(sourceFile); } - return result; } - function getPathUpdater(oldFilePath, newFilePath, host) { - var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importLiteral, importingSourceFile, program, host, oldToNew) { + var symbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + if (symbol) { + if (symbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; + var oldFileName = ts.find(symbol.declarations, ts.isSourceFile).fileName; + return oldToNew(oldFileName) || oldFileName; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, program); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, program) { + return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); + function getIfInProgram(oldLocation) { + var newLocation = oldToNew(oldLocation); + return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) + ? newLocation || oldLocation + : undefined; + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } } function createStringRange(node, sourceFile) { return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -77157,7 +77396,8 @@ var ts; addInferredTypings(module_1, "Inferred typings from unresolved imports"); } packageNameToTypingLocation.forEach(function (typing, name) { - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && isTypingUpToDate(typing, typesRegistry.get(name))) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { inferredTypings.set(name, typing.typingLocation); } }); @@ -77323,7 +77563,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_15 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { return "continue"; @@ -77334,7 +77574,7 @@ var ts; }; for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { var sourceFile = sourceFiles_7[_i]; - _loop_14(sourceFile); + _loop_15(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -78570,13 +78810,13 @@ var ts; } function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_16 = 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_15(start); + var state_4 = _loop_16(start); if (typeof state_4 === "object") return state_4.value; } @@ -79149,7 +79389,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -79163,7 +79403,7 @@ var ts; }; for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { var declaration = declarations_13[_b]; - var state_5 = _loop_16(declaration); + var state_5 = _loop_17(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -80156,7 +80396,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_18 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -80172,7 +80412,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_18(opt); } return options; } @@ -82530,6 +82770,12 @@ var ts; this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); if (!containingList) { @@ -82735,7 +82981,7 @@ var ts; else if (ts.isStatement(node) || ts.isClassOrTypeElement(node)) { return { suffix: this.newLineCharacter }; } - else if (ts.isVariableDeclaration(node)) { + else if (ts.isVariableDeclaration(node) || ts.isStringLiteral(node)) { return { prefix: ", " }; } else if (ts.isPropertyAssignment(node)) { @@ -82884,13 +83130,13 @@ var ts; return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; 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) { + var _loop_19 = 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); }); }; for (var i = 0; i < normalized.length - 1; i++) { - _loop_18(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -82901,7 +83147,7 @@ var ts; changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6, true); var changes = ts.formatting.formatDocument(sourceFile, formatContext); var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; @@ -83610,18 +83856,18 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); } } }); return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -83631,7 +83877,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, undefined, moduleSpecifier, preferences)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, undefined, moduleSpecifier, quotePreference)); break; case 186: if (ts.isRequireCall(importNode, false)) { @@ -83641,14 +83887,14 @@ var ts; } } } - function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -83682,17 +83928,17 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { case 213: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; case 215: { var expression = statement.expression; switch (expression.kind) { case 186: { if (ts.isRequireCall(expression, true)) { - changes.replaceNode(sourceFile, statement, ts.makeImport(undefined, undefined, expression.arguments[0], preferences)); + changes.replaceNode(sourceFile, statement, ts.makeImport(undefined, undefined, expression.arguments[0], quotePreference)); } return false; } @@ -83706,7 +83952,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -83718,11 +83964,11 @@ var ts; } else if (ts.isRequireCall(initializer, true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); } } return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); @@ -83731,18 +83977,18 @@ var ts; changes.replaceNodeWithNodes(sourceFile, statement, newNodes); } } - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { case 179: case 180: { var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst(undefined, name, ts.createIdentifier(tmp)), ]; } case 71: - return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: ts.Debug.assertNever(name); } @@ -83858,7 +84104,7 @@ var ts; return makeConst(modifiers, ts.createIdentifier(name), exported); } } - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { case 179: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -83867,23 +84113,23 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(undefined, importSpecifiers, moduleSpecifier, preferences)]; + return [ts.makeImport(undefined, importSpecifiers, moduleSpecifier, quotePreference)]; } } case 180: { var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier, preferences), + ts.makeImport(ts.createIdentifier(tmp), undefined, moduleSpecifier, quotePreference), makeConst(undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: ts.Debug.assertNever(name); } } - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); var namedBindingsNames = ts.createMap(); var needDefaultImport = false; @@ -83914,7 +84160,7 @@ var ts; if (!namedBindings) { needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; } function makeUniqueName(name, identifiers) { while (identifiers.original.has(name) || identifiers.additional.has(name)) { @@ -83950,10 +84196,10 @@ var ts; function classExpressionToDeclaration(name, additionalModifiers, cls) { return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier, preferences) - : ts.makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); + ? ts.makeImport(ts.createIdentifier(localName), undefined, moduleSpecifier, quotePreference) + : ts.makeImport(undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -84178,7 +84424,7 @@ var ts; var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifierWithoutQuotes, ts.getQuotePreference(sourceFile, preferences)); var importDecl = importKind !== 3 ? ts.createImportDeclaration(undefined, undefined, createImportClauseOfKind(importKind, symbolName), quotedModuleSpecifier) : ts.createImportEqualsDeclaration(undefined, undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); @@ -84192,15 +84438,6 @@ var ts; }); return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - function shouldUseSingleQuote(sourceFile, preferences) { - if (preferences.quotePreference) { - return preferences.quotePreference === "single"; - } - else { - var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); - return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); - } - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -86229,7 +86466,7 @@ var ts; var namespace = ts.getNamespaceDeclarationNode(node); var opts = context.program.getCompilerOptions(); var variations = []; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, undefined, node.moduleSpecifier, context.preferences))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)))); } @@ -86386,50 +86623,69 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { - function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + function getModuleSpecifier(program, fromSourceFile, fromSourceFileName, toFileName, host, preferences) { + var info = getInfo(program.getCompilerOptions(), fromSourceFile, fromSourceFileName, host); 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]; - } - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return getGlobalModuleSpecifier(toFileName, info, host, compilerOptions) || + ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [[ambient]]; + var compilerOptions = program.getCompilerOptions(); + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.fileName, host); + var modulePaths = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); + return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { + return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { + var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || compilerOptions.rootDirs && tryGetModuleNameFromRootDirs(compilerOptions.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + } + function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { + var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + 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]; + } + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { @@ -86686,7 +86942,7 @@ var ts; } } function doChange(changes, sourceFile, info, preferences) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, undefined, info.moduleSpecifier, preferences)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -87237,7 +87493,7 @@ var ts; var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); var file = scope.getSourceFile(); - var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; @@ -87403,7 +87659,7 @@ var ts; var substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); var file = scope.getSourceFile(); - var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined @@ -87743,7 +87999,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_20 = function (i) { var scopeUsages = usagesPerScope[i]; if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { var errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; @@ -87779,7 +88035,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_20(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -88095,8 +88351,8 @@ var ts; return undefined; 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); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), @@ -88192,14 +88448,17 @@ var ts; return undefined; var startStatement = statements[startNodeIndex]; if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { - return [statements[startNodeIndex]]; + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; } if (range.pos > startStatement.getStart(file)) return undefined; var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; } function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); @@ -88208,7 +88467,7 @@ var ts; var extension = ts.extensionFromPath(oldFile.fileName); var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); var newFileNameWithExtension = newModuleName + extension; - changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); } function getStatementsToMove(context) { @@ -88217,10 +88476,11 @@ var ts; return undefined; var all = []; var ranges = []; - 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] }); + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); }); return all.length === 0 ? undefined : { all: all, ranges: ranges }; } @@ -88250,26 +88510,27 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { 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, preferences); + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); if (importsFromNewFile) { changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, 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, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).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); + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -88282,11 +88543,13 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_21 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_22 = function (statement) { forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) ? ts.getPropertySymbolFromBindingElement(checker, name.parent) @@ -88298,16 +88561,67 @@ var ts; var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); }); }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_22(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_21(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 243: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 245 ? + node.importClause.namedBindings.name : undefined; + case 242: + return node.name; + case 231: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863, true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 243: + return ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 242: + return ts.createImportEqualsDeclaration(undefined, undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 231: + return ts.createVariableDeclaration(newNamespaceId, undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { @@ -88334,7 +88648,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -88345,13 +88659,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { path = ts.ensurePathIsNonModuleName(path); if (useEs6Imports) { var specifiers = imports.map(function (i) { return ts.createImportSpecifier(undefined, ts.createIdentifier(i)); }); - return ts.makeImportIfNecessary(defaultImport, specifiers, path, preferences); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); } else { ts.Debug.assert(!defaultImport); @@ -88450,7 +88764,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -88481,7 +88795,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -89791,9 +90105,9 @@ 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 _a; var syntaxTreeCache = new SyntaxTreeCache(host); var program; var lastProjectVersion; @@ -90406,8 +90720,9 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } - function getEditsForFileRename(oldFilePath, newFilePath, formatOptions) { - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions)); + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -93061,6 +93376,10 @@ var ts; } return this.program.getSourceFileByPath(path); }; + Project.prototype.getSourceFileOrConfigFile = function (path) { + var options = this.program.getCompilerOptions(); + return path === options.configFilePath ? options.configFile : this.getSourceFile(path); + }; Project.prototype.close = function () { var _this = this; if (this.program) { @@ -93471,7 +93790,7 @@ var ts; } var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_22 = function (globalPluginName) { + var _loop_23 = function (globalPluginName) { if (!globalPluginName) return "continue"; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) @@ -93482,7 +93801,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_22(globalPluginName); + _loop_23(globalPluginName); } } }; @@ -94278,7 +94597,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_23 = function (inferredProject) { + var _loop_24 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -94290,7 +94609,7 @@ var ts; }; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_23(inferredProject); + _loop_24(inferredProject); } } return project; @@ -94873,7 +95192,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_24 = function (project) { + var _loop_25 = function (project) { if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && @@ -94889,7 +95208,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_24(project); + _loop_25(project); } } } @@ -95134,13 +95453,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_25 = function (proj) { + var _loop_26 = 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_25(proj); + _loop_26(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -95240,7 +95559,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_26 = function (name) { + var _loop_27 = function (name) { var rule = this_2.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -95255,7 +95574,7 @@ var ts; } } if (rule.exclude) { - var _loop_28 = function (exclude) { + var _loop_29 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -95278,7 +95597,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_28(exclude); + _loop_29(exclude); } } else { @@ -95293,11 +95612,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_26(name); + _loop_27(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_27 = function (i) { + var _loop_28 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -95331,7 +95650,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_27(i); + _loop_28(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -96087,6 +96406,7 @@ var ts; } var _a = checkList[index], fileName = _a.fileName, project = _a.project; index++; + project.updateGraph(); if (!project.containsFile(fileName, requireOpen)) { return; } @@ -97043,7 +97363,7 @@ var ts; }; Session.prototype.getEditsForFileRename = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var changes = project.getLanguageService().getEditsForFileRename(args.oldFilePath, args.newFilePath, this.getFormatOptions(file)); + var changes = project.getLanguageService().getEditsForFileRename(args.oldFilePath, args.newFilePath, this.getFormatOptions(file), this.getPreferences(file)); return simplifiedResult ? this.mapTextChangesToCodeEdits(project, changes) : changes; }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { @@ -97106,20 +97426,10 @@ var ts; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; - return textChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); - }; - Session.prototype.mapTextChangesToCodeEditsUsingScriptinfo = function (textChanges, scriptInfo) { - var _this = this; - 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); - } + return textChanges.map(function (change) { + var path = server.normalizedPathToPath(server.toNormalizedPath(change.fileName), _this.host.getCurrentDirectory(), function (fileName) { return _this.getCanonicalFileName(fileName); }); + return mapTextChangesToCodeEdits(change, project.getSourceFileOrConfigFile(path)); + }); }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -97128,12 +97438,6 @@ 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; @@ -97282,6 +97586,31 @@ var ts; return Session; }()); server.Session = Session; + function mapTextChangesToCodeEdits(textChanges, sourceFile) { + ts.Debug.assert(!!textChanges.isNewFile === !sourceFile); + if (sourceFile) { + return { + fileName: textChanges.fileName, + textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, sourceFile); }), + }; + } + else { + return convertNewFileTextChangeToCodeEdit(textChanges); + } + } + function convertTextChangeToCodeEdit(change, sourceFile) { + return { + start: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start)), + end: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start + change.span.length)), + newText: change.newText ? change.newText : "", + }; + } + function convertNewFileTextChangeToCodeEdit(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 }] }; + } function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { var newText = applyEdits(oldText, renameFilename, edits); var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index e5ac29026ce..cee46538461 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -714,10 +714,14 @@ declare namespace ts { kind: SyntaxKind.ThisType; } type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionTypeNode extends TypeNode, SignatureDeclarationBase { + interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; + type: TypeNode; + } + interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.FunctionType; } - interface ConstructorTypeNode extends TypeNode, SignatureDeclarationBase { + interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.ConstructorType; } interface NodeWithTypeArguments extends TypeNode { @@ -4154,18 +4158,18 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; @@ -4564,7 +4568,7 @@ declare namespace ts { getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; - getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings): ReadonlyArray; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -8519,9 +8523,7 @@ declare namespace ts.server { private mapCodeAction; private mapCodeFixAction; private mapTextChangesToCodeEdits; - private mapTextChangesToCodeEditsUsingScriptinfo; private convertTextChangeToCodeEdit; - private convertNewFileTextChangeToCodeEdit; private getBraceMatching; private getDiagnosticsForProject; getCanonicalFileName(fileName: string): string; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index bd460361048..4ea0f4f7fdc 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1635,7 +1635,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -3938,6 +3938,23 @@ var ts; return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function tryRemoveDirectoryPrefix(path, dirPath) { + var a = tryRemovePrefix(path, dirPath); + if (a === undefined) + return undefined; + switch (a.charCodeAt(0)) { + case 47 /* slash */: + case 92 /* backslash */: + return a.slice(1); + default: + return undefined; + } + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3947,6 +3964,10 @@ var ts; return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; } ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; function stringContains(str, substring) { return str.indexOf(substring) !== -1; } @@ -4106,6 +4127,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } + /** @param path directory of the tsconfig.json */ function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); @@ -4119,14 +4141,18 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); // Associate an array of results with each include regex. This keeps results in order of the "include" order. // If there are no "includes", then just put everything in results[0]. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; @@ -9265,11 +9291,6 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -9696,7 +9717,7 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { + return objectLiteral.properties.filter(function (property) { if (property.kind === 269 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); @@ -9712,15 +9733,18 @@ var ts; } 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; - }); + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, 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 getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -14748,7 +14772,6 @@ var ts; 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 = {})); @@ -15447,6 +15470,7 @@ var ts; 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); + sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); var pos = getNodePos(); @@ -15900,8 +15924,8 @@ var ts; kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { addJSDocComment(node); } @@ -16754,6 +16778,23 @@ var ts; } return finishNode(node); } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 161 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 162 /* FunctionType */: + case 163 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + // parameters.pos === parameters.end only if we used parseMissingList, else should contain at least `()` + return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type); + } + case 172 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); var node = createNode(160 /* TypePredicate */, lhs.pos); @@ -16924,18 +16965,20 @@ var ts; return finishNode(node); } /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. * @returns If return type parsing succeeds */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + var parametersParsedSuccessfully = parseParameterList(signature, flags); if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { signature.type = parseTypeOrTypePredicate(); - return signature.type !== undefined; + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; } - return true; + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -16953,7 +16996,8 @@ var ts; } return false; } - function parseParameterList(flags) { + // Returns true on success. + function parseParameterList(signature, flags) { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -16967,25 +17011,18 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(19 /* OpenParenToken */)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1 /* Yield */)); - setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { - // Caller insisted that we had to end with a ) We didn't. So just return - // undefined here. - return undefined; - } - return result; + if (!parseExpected(19 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; } - // We didn't even have an open paren. If the caller requires a complete parameter list, - // we definitely can't provide that. However, if they're ok with an incomplete one, - // then just return an empty set of parameters. - return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. @@ -17214,23 +17251,14 @@ var ts; var node = createNode(172 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); - if (!node.type) { - return undefined; - } parseExpected(20 /* CloseParenToken */); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163 /* ConstructorType */) { - parseExpected(94 /* NewKeyword */); - } - if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) { - return undefined; - } - if (!node.parameters) { - return undefined; - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94 /* NewKeyword */) ? 163 /* ConstructorType */ : 162 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { @@ -17546,11 +17574,8 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); - } - if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(163 /* ConstructorType */); + if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { @@ -17981,11 +18006,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - 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) { + if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -25076,6 +25097,9 @@ var ts; } break; case 224 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; case 222 /* ContinueStatement */: case 223 /* BreakStatement */: transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -27689,8 +27713,14 @@ var ts; break; } } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - break loop; + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } } break; case 237 /* EnumDeclaration */: @@ -27822,9 +27852,8 @@ var ts; 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; + location = ts.getJSDocHost(location); + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -28113,7 +28142,7 @@ var ts; : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } function isSyntacticDefault(node) { - return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */)); + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { @@ -28783,6 +28812,43 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainerOfSymbol(symbol) { + var container = getParentOfSymbol(symbol); + if (container) { + return container; + } + var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!candidate) { + return undefined; + } + var alias = getAliasForSymbolInContainer(candidate, symbol); + return alias ? candidate : undefined; + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? getMergedSymbol(symbol.exportSymbol) @@ -29058,7 +29124,7 @@ var ts; // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); + symbol = getContainerOfSymbol(symbol); } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named @@ -29690,9 +29756,13 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); - if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + } } } var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); @@ -29876,12 +29946,12 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); if (parent) { var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); } } } @@ -34887,12 +34957,13 @@ var ts; return links.resolvedType; } function resolveImportSymbolType(node, links, symbol, meaning) { - links.resolvedSymbol = symbol; + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; if (meaning === 67216319 /* Value */) { - return links.resolvedType = getTypeOfSymbol(symbol); + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { - return links.resolvedType = getTypeReferenceType(node, symbol); + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol } } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { @@ -42757,7 +42828,7 @@ var ts; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = undefined; + typeArguments = node.typeArguments; if (node.template.kind === 201 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. @@ -43578,6 +43649,7 @@ var ts; if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { + ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc return anySignature; } if (superType !== unknownType) { @@ -45517,6 +45589,9 @@ var ts; node.contextualType = saveContextualType; return type; } + function checkExpresionNoReturn(node) { + checkExpression(node); + } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -47248,7 +47323,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; 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)); + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -57597,7 +57672,7 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; @@ -58925,7 +59000,8 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && - !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -60068,6 +60144,7 @@ var ts; case 165 /* TypeLiteral */: case 119 /* AnyKeyword */: case 173 /* ThisType */: + case 178 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); @@ -61949,6 +62026,8 @@ var ts; return visitAwaitExpression(node); case 202 /* YieldExpression */: return visitYieldExpression(node); + case 224 /* ReturnStatement */: + return visitReturnStatement(node); case 227 /* LabeledStatement */: return visitLabeledStatement(node); case 183 /* ObjectLiteralExpression */: @@ -62008,6 +62087,12 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); @@ -62184,7 +62269,7 @@ var ts; ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), + /*statement*/ convertForOfStatementHead(node, getValue)), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -64384,6 +64469,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; + var leadingStatements = []; var statements = []; var body = node.body; var statementOffset; @@ -64391,18 +64477,14 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); - // If we added any generated statements, this must be a multi-line block. - if (!multiLine && statements.length > 0) { - multiLine = true; + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -64440,10 +64522,10 @@ var ts; ts.prependStatements(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) { + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -68850,7 +68932,7 @@ var ts; name: "typescript:generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); /*@internal*/ @@ -73632,7 +73714,7 @@ var ts; * @param sourceFileOrBundle The input source file or bundle for the program. */ function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled) { + if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { return; } if (sourceMapData) { @@ -73755,7 +73837,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos)) { + if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { return; } if (extendedDiagnostics) { @@ -73804,7 +73886,7 @@ var ts; * @param emitCallback The callback used to emit the node. */ function emitNodeWithSourceMap(hint, node, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { @@ -73853,7 +73935,7 @@ var ts; * @param emitCallback The callback used to emit the token. */ function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; @@ -73871,6 +73953,9 @@ var ts; } return tokenPos; } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } /** * Set the current source file. * @@ -73882,6 +73967,9 @@ var ts; } currentSource = sourceFile; currentSourceText = currentSource.text; + if (isJsonSourceMapSource(sourceFile)) { + return; + } // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location @@ -73903,7 +73991,7 @@ var ts; * Gets the text for the source map. */ function getText() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } encodeLastRecordedSourceMapSpan(); @@ -73921,7 +74009,7 @@ var ts; * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } if (compilerOptions.inlineSourceMap) { @@ -74383,7 +74471,7 @@ var ts; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; @@ -75620,7 +75708,7 @@ var ts; increaseIndent(); } var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); @@ -79434,11 +79522,9 @@ var ts; else if (ts.isLiteralImportTypeNode(node)) { imports = ts.append(imports, node.argument.literal); } - else { - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); - } + collectDynamicImportOrRequireCallsForEachChild(node); + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); } } function collectDynamicImportOrRequireCallsForEachChild(node) { @@ -81185,8 +81271,29 @@ var ts; function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } - function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { - for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; if (searchIndex === 0) { // Folder isnt at expected minimun levels @@ -81195,14 +81302,6 @@ var ts; } return true; } - function canWatchDirectory(dirPath) { - return isDirectoryAtleastAtLevelFromFSRoot(dirPath, - // When root is "/" do not watch directories like: - // "/", "/user", "/user/username", "/user/username/folderAtRoot" - // When root is "c:/" do not watch directories like: - // "c:/", "c:/folderAtRoot" - dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); - } function filterFSRootDirectoriesToWatch(watchPath, dirPath) { if (!canWatchDirectory(dirPath)) { watchPath.ignore = true; @@ -81709,11 +81808,11 @@ 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]; } + var _a; return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, @@ -83146,6 +83245,7 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + /** @internal */ function getOptionFromName(optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); @@ -83159,6 +83259,7 @@ var ts; } return optionNameMap.get(optionName); } + ts.getOptionFromName = getOptionFromName; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -85747,18 +85848,37 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { 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, preferences.quotePreference === "single") : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); } ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile) ? 0 /* Single */ : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -86122,9 +86242,9 @@ var ts; return node.forEachChild(function (child) { return child; }); } /* @internal */ - function getUniqueName(baseName, fileText) { + function getUniqueName(baseName, sourceFile) { var nameText = baseName; - for (var i = 1; ts.stringContains(fileText, nameText); i++) { + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { nameText = baseName + "_" + i; } return nameText; @@ -86145,7 +86265,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = newText.indexOf(name); + var index = indexInTextChange(newText, name); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -86162,6 +86282,17 @@ var ts; return lastPos; } ts.getRenameLocation = getRenameLocation; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -87964,7 +88095,7 @@ var ts; return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; - var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -91139,19 +91270,28 @@ var ts; } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { - var symbol = checker.getSymbolAtLocation(definition); - if (!symbol) - return true; // Be lenient with invalid code. - return getPossibleSymbolReferenceNodes(sourceFile, symbol.name).some(function (token) { - if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) - return false; - var referenceSymbol = checker.getSymbolAtLocation(token); - return referenceSymbol === symbol - || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol - || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol; - }); + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos, /*includeJsDocComment*/ true); }); @@ -91892,66 +92032,180 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - 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) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } + updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); }); } ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var canonicalPath = getCanonicalFileName(path); + if (canonicalPath === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(canonicalPath, canonicalOldPath); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + }; + } + function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var result = []; + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + var _loop_14 = function (sourceFile) { + var newImportFromPath = oldToNew(sourceFile.fileName) || sourceFile.fileName; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) + : getSourceFileToImport(importLiteral, sourceFile, program, host, oldToNew); + return toImport === undefined ? undefined : ts.moduleSpecifiers.getModuleSpecifier(program, sourceFile, newImportFromPath, toImport, host, preferences); + }); + }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations - if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } + _loop_14(sourceFile); } - return result; } - 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.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importLiteral, importingSourceFile, program, host, oldToNew) { + var symbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + if (symbol) { + if (symbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; // No need to update if it's an ambient module + var oldFileName = ts.find(symbol.declarations, ts.isSourceFile).fileName; + return oldToNew(oldFileName) || oldFileName; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, program); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, program) { + return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); + function getIfInProgram(oldLocation) { + var newLocation = oldToNew(oldLocation); + return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) + ? newLocation || oldLocation + : undefined; + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } } function createStringRange(node, sourceFile) { return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -92743,7 +92997,8 @@ var ts; } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typing, name) { - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && isTypingUpToDate(typing, typesRegistry.get(name))) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { inferredTypings.set(name, typing.typingLocation); } }); @@ -92937,7 +93192,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_15 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -92949,7 +93204,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { var sourceFile = sourceFiles_7[_i]; - _loop_14(sourceFile); + _loop_15(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -94430,13 +94685,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_16 = 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_15(start); + var state_4 = _loop_16(start); if (typeof state_4 === "object") return state_4.value; } @@ -95104,7 +95359,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -95118,7 +95373,7 @@ var ts; }; for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { var declaration = declarations_13[_b]; - var state_5 = _loop_16(declaration); + var state_5 = _loop_17(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -96273,7 +96528,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_18 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -96292,7 +96547,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_18(opt); } return options; } @@ -99064,6 +99319,12 @@ var ts; this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); if (!containingList) { @@ -99281,7 +99542,7 @@ var ts; else if (ts.isStatement(node) || ts.isClassOrTypeElement(node)) { return { suffix: this.newLineCharacter }; } - else if (ts.isVariableDeclaration(node)) { + else if (ts.isVariableDeclaration(node) || ts.isStringLiteral(node)) { return { prefix: ", " }; } else if (ts.isPropertyAssignment(node)) { @@ -99496,14 +99757,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_19 = 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_18(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -99515,7 +99776,7 @@ var ts; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); var changes = ts.formatting.formatDocument(sourceFile, formatContext); var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; @@ -100272,11 +100533,11 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); } } }); @@ -100284,7 +100545,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100294,7 +100555,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100305,14 +100566,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100347,10 +100608,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100358,7 +100619,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, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } @@ -100373,7 +100634,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100386,11 +100647,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100402,20 +100663,20 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: ts.Debug.assertNever(name); } @@ -100557,7 +100818,7 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { case 179 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -100566,7 +100827,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100577,12 +100838,12 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: ts.Debug.assertNever(name); } @@ -100591,7 +100852,7 @@ var ts; * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -100626,7 +100887,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100666,10 +100927,10 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -100918,7 +101179,7 @@ var ts; var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifierWithoutQuotes, ts.getQuotePreference(sourceFile, preferences)); var importDecl = importKind !== 3 /* Equals */ ? ts.createImportDeclaration( /*decorators*/ undefined, @@ -100939,15 +101200,6 @@ var ts; // are there are already a new line seperating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - function shouldUseSingleQuote(sourceFile, preferences) { - if (preferences.quotePreference) { - return preferences.quotePreference === "single"; - } - else { - var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); - return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); - } - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -103171,7 +103423,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103334,78 +103586,99 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + // Note: fromSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(program, fromSourceFile, fromSourceFileName, toFileName, host, preferences) { + var info = getInfo(program.getCompilerOptions(), fromSourceFile, fromSourceFileName, host); + var compilerOptions = program.getCompilerOptions(); + return getGlobalModuleSpecifier(toFileName, info, host, compilerOptions) || + ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; // For each symlink/original for a module, returns a list of ways to import that file. function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [[ambient]]; 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]; + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.fileName, host); + var modulePaths = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); + return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { + return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { + var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || compilerOptions.rootDirs && tryGetModuleNameFromRootDirs(compilerOptions.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + } + function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { + var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + 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]; + } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { @@ -103681,7 +103954,7 @@ var ts; } } function doChange(changes, sourceFile, info, preferences) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -104327,7 +104600,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; @@ -104543,7 +104816,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted variable var file = scope.getSourceFile(); - var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined @@ -104936,7 +105209,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_20 = 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 @@ -104976,7 +105249,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_20(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -105333,8 +105606,8 @@ var ts; return undefined; 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); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), @@ -105438,7 +105711,7 @@ var ts; return undefined; var startStatement = statements[startNodeIndex]; if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { - return [statements[startNodeIndex]]; + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; } // Can't only partially include the start node or be partially into the next node if (range.pos > startStatement.getStart(file)) @@ -105447,7 +105720,10 @@ var ts; // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; } function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); @@ -105457,7 +105733,7 @@ var ts; 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, preferences)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); 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. @@ -105467,10 +105743,11 @@ var ts; return undefined; var all = []; var ranges = []; - 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] }); + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); }); return all.length === 0 ? undefined : { all: all, ranges: ranges }; } @@ -105500,26 +105777,27 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { 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, preferences); + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); 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, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).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); + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -105532,11 +105810,13 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_21 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_22 = function (statement) { forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) ? ts.getPropertySymbolFromBindingElement(checker, name.parent) @@ -105548,16 +105828,68 @@ var ts; var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); }); }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_22(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_21(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 243 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 245 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 242 /* ImportEqualsDeclaration */: + return node.name; + case 231 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 243 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 242 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 231 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { @@ -105584,7 +105916,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -105595,13 +105927,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { 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, preferences); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105700,7 +106032,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105732,7 +106064,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -107147,9 +107479,9 @@ 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 _a; var syntaxTreeCache = new SyntaxTreeCache(host); var program; var lastProjectVersion; @@ -107859,8 +108191,9 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } - function getEditsForFileRename(oldFilePath, newFilePath, formatOptions) { - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions)); + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -111007,6 +111340,11 @@ var ts; } return this.program.getSourceFileByPath(path); }; + /* @internal */ + Project.prototype.getSourceFileOrConfigFile = function (path) { + var options = this.program.getCompilerOptions(); + return path === options.configFilePath ? options.configFile : this.getSourceFile(path); + }; Project.prototype.close = function () { var _this = this; if (this.program) { @@ -111478,7 +111816,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_22 = function (globalPluginName) { + var _loop_23 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -111493,7 +111831,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_22(globalPluginName); + _loop_23(globalPluginName); } } }; @@ -112471,7 +112809,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_23 = function (inferredProject) { + var _loop_24 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -112492,7 +112830,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_23(inferredProject); + _loop_24(inferredProject); } } return project; @@ -113220,7 +113558,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_24 = function (project) { + var _loop_25 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -113237,7 +113575,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_24(project); + _loop_25(project); } } } @@ -113576,13 +113914,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_25 = function (proj) { + var _loop_26 = 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_25(proj); + _loop_26(proj); } }; /* @internal */ @@ -113691,7 +114029,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_26 = function (name) { + var _loop_27 = 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]; @@ -113709,7 +114047,7 @@ var ts; } } if (rule_2.exclude) { - var _loop_28 = function (exclude) { + var _loop_29 = function (exclude) { var processedRule = root.replace(rule_2.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -113736,7 +114074,7 @@ var ts; }; for (var _c = 0, _d = rule_2.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_28(exclude); + _loop_29(exclude); } } else { @@ -113752,11 +114090,11 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_26(name); + _loop_27(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_27 = function (i) { + var _loop_28 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -113794,7 +114132,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_27(i); + _loop_28(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -114596,6 +114934,8 @@ var ts; } var _a = checkList[index], fileName = _a.fileName, project = _a.project; index++; + // Ensure the project is upto date before checking if this file is present in the project + project.updateGraph(); if (!project.containsFile(fileName, requireOpen)) { return; } @@ -115591,7 +115931,7 @@ var ts; }; Session.prototype.getEditsForFileRename = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var changes = project.getLanguageService().getEditsForFileRename(args.oldFilePath, args.newFilePath, this.getFormatOptions(file)); + var changes = project.getLanguageService().getEditsForFileRename(args.oldFilePath, args.newFilePath, this.getFormatOptions(file), this.getPreferences(file)); return simplifiedResult ? this.mapTextChangesToCodeEdits(project, changes) : changes; }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { @@ -115655,20 +115995,10 @@ var ts; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; - return textChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); - }; - Session.prototype.mapTextChangesToCodeEditsUsingScriptinfo = function (textChanges, scriptInfo) { - var _this = this; - 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); - } + return textChanges.map(function (change) { + var path = server.normalizedPathToPath(server.toNormalizedPath(change.fileName), _this.host.getCurrentDirectory(), function (fileName) { return _this.getCanonicalFileName(fileName); }); + return mapTextChangesToCodeEdits(change, project.getSourceFileOrConfigFile(path)); + }); }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { @@ -115677,12 +116007,6 @@ 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; @@ -115838,6 +116162,31 @@ var ts; return Session; }()); server.Session = Session; + function mapTextChangesToCodeEdits(textChanges, sourceFile) { + ts.Debug.assert(!!textChanges.isNewFile === !sourceFile); + if (sourceFile) { + return { + fileName: textChanges.fileName, + textChanges: textChanges.textChanges.map(function (textChange) { return convertTextChangeToCodeEdit(textChange, sourceFile); }), + }; + } + else { + return convertNewFileTextChangeToCodeEdit(textChanges); + } + } + function convertTextChangeToCodeEdit(change, sourceFile) { + return { + start: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start)), + end: convertToLocation(sourceFile.getLineAndCharacterOfPosition(change.span.start + change.span.length)), + newText: change.newText ? change.newText : "", + }; + } + function convertNewFileTextChangeToCodeEdit(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 }] }; + } /* @internal */ // Exported only for tests function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { var newText = applyEdits(oldText, renameFilename, edits); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 2ac57dfce79..8685c813ffc 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -714,10 +714,14 @@ declare namespace ts { kind: SyntaxKind.ThisType; } type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionTypeNode extends TypeNode, SignatureDeclarationBase { + interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; + type: TypeNode; + } + interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.FunctionType; } - interface ConstructorTypeNode extends TypeNode, SignatureDeclarationBase { + interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.ConstructorType; } interface NodeWithTypeArguments extends TypeNode { @@ -4154,18 +4158,18 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; @@ -4564,7 +4568,7 @@ declare namespace ts { getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; - getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings): ReadonlyArray; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; diff --git a/lib/typescript.js b/lib/typescript.js index 7bf5c7f971d..78fc16846f8 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1635,7 +1635,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -3938,6 +3938,23 @@ var ts; return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function tryRemoveDirectoryPrefix(path, dirPath) { + var a = tryRemovePrefix(path, dirPath); + if (a === undefined) + return undefined; + switch (a.charCodeAt(0)) { + case 47 /* slash */: + case 92 /* backslash */: + return a.slice(1); + default: + return undefined; + } + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3947,6 +3964,10 @@ var ts; return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; } ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; function stringContains(str, substring) { return str.indexOf(substring) !== -1; } @@ -4106,6 +4127,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } + /** @param path directory of the tsconfig.json */ function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); @@ -4119,14 +4141,18 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); // Associate an array of results with each include regex. This keeps results in order of the "include" order. // If there are no "includes", then just put everything in results[0]. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; @@ -9265,11 +9291,6 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -9696,7 +9717,7 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { + return objectLiteral.properties.filter(function (property) { if (property.kind === 269 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); @@ -9712,15 +9733,18 @@ var ts; } 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; - }); + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, 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 getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -14748,7 +14772,6 @@ var ts; 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 = {})); @@ -15447,6 +15470,7 @@ var ts; 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); + sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); var pos = getNodePos(); @@ -15900,8 +15924,8 @@ var ts; kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { addJSDocComment(node); } @@ -16754,6 +16778,23 @@ var ts; } return finishNode(node); } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 161 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 162 /* FunctionType */: + case 163 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + // parameters.pos === parameters.end only if we used parseMissingList, else should contain at least `()` + return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type); + } + case 172 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); var node = createNode(160 /* TypePredicate */, lhs.pos); @@ -16924,18 +16965,20 @@ var ts; return finishNode(node); } /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. * @returns If return type parsing succeeds */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + var parametersParsedSuccessfully = parseParameterList(signature, flags); if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { signature.type = parseTypeOrTypePredicate(); - return signature.type !== undefined; + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; } - return true; + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -16953,7 +16996,8 @@ var ts; } return false; } - function parseParameterList(flags) { + // Returns true on success. + function parseParameterList(signature, flags) { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -16967,25 +17011,18 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(19 /* OpenParenToken */)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1 /* Yield */)); - setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { - // Caller insisted that we had to end with a ) We didn't. So just return - // undefined here. - return undefined; - } - return result; + if (!parseExpected(19 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; } - // We didn't even have an open paren. If the caller requires a complete parameter list, - // we definitely can't provide that. However, if they're ok with an incomplete one, - // then just return an empty set of parameters. - return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. @@ -17214,23 +17251,14 @@ var ts; var node = createNode(172 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); - if (!node.type) { - return undefined; - } parseExpected(20 /* CloseParenToken */); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163 /* ConstructorType */) { - parseExpected(94 /* NewKeyword */); - } - if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) { - return undefined; - } - if (!node.parameters) { - return undefined; - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94 /* NewKeyword */) ? 163 /* ConstructorType */ : 162 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { @@ -17546,11 +17574,8 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); - } - if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(163 /* ConstructorType */); + if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { @@ -17981,11 +18006,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - 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) { + if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -25076,6 +25097,9 @@ var ts; } break; case 224 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; case 222 /* ContinueStatement */: case 223 /* BreakStatement */: transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -27689,8 +27713,14 @@ var ts; break; } } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - break loop; + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } } break; case 237 /* EnumDeclaration */: @@ -27822,9 +27852,8 @@ var ts; 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; + location = ts.getJSDocHost(location); + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -28113,7 +28142,7 @@ var ts; : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } function isSyntacticDefault(node) { - return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */)); + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { @@ -28783,6 +28812,43 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainerOfSymbol(symbol) { + var container = getParentOfSymbol(symbol); + if (container) { + return container; + } + var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!candidate) { + return undefined; + } + var alias = getAliasForSymbolInContainer(candidate, symbol); + return alias ? candidate : undefined; + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? getMergedSymbol(symbol.exportSymbol) @@ -29058,7 +29124,7 @@ var ts; // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); + symbol = getContainerOfSymbol(symbol); } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named @@ -29690,9 +29756,13 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); - if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + } } } var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); @@ -29876,12 +29946,12 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); if (parent) { var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); } } } @@ -34887,12 +34957,13 @@ var ts; return links.resolvedType; } function resolveImportSymbolType(node, links, symbol, meaning) { - links.resolvedSymbol = symbol; + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; if (meaning === 67216319 /* Value */) { - return links.resolvedType = getTypeOfSymbol(symbol); + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { - return links.resolvedType = getTypeReferenceType(node, symbol); + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol } } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { @@ -42757,7 +42828,7 @@ var ts; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = undefined; + typeArguments = node.typeArguments; if (node.template.kind === 201 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. @@ -43578,6 +43649,7 @@ var ts; if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { + ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc return anySignature; } if (superType !== unknownType) { @@ -45517,6 +45589,9 @@ var ts; node.contextualType = saveContextualType; return type; } + function checkExpresionNoReturn(node) { + checkExpression(node); + } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -47248,7 +47323,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; 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)); + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -57597,7 +57672,7 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; @@ -58925,7 +59000,8 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && - !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -60068,6 +60144,7 @@ var ts; case 165 /* TypeLiteral */: case 119 /* AnyKeyword */: case 173 /* ThisType */: + case 178 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); @@ -61949,6 +62026,8 @@ var ts; return visitAwaitExpression(node); case 202 /* YieldExpression */: return visitYieldExpression(node); + case 224 /* ReturnStatement */: + return visitReturnStatement(node); case 227 /* LabeledStatement */: return visitLabeledStatement(node); case 183 /* ObjectLiteralExpression */: @@ -62008,6 +62087,12 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); @@ -62184,7 +62269,7 @@ var ts; ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), + /*statement*/ convertForOfStatementHead(node, getValue)), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -64384,6 +64469,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; + var leadingStatements = []; var statements = []; var body = node.body; var statementOffset; @@ -64391,18 +64477,14 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); - // If we added any generated statements, this must be a multi-line block. - if (!multiLine && statements.length > 0) { - multiLine = true; + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -64440,10 +64522,10 @@ var ts; ts.prependStatements(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) { + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -68850,7 +68932,7 @@ var ts; name: "typescript:generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); /*@internal*/ @@ -73632,7 +73714,7 @@ var ts; * @param sourceFileOrBundle The input source file or bundle for the program. */ function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled) { + if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { return; } if (sourceMapData) { @@ -73755,7 +73837,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos)) { + if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { return; } if (extendedDiagnostics) { @@ -73804,7 +73886,7 @@ var ts; * @param emitCallback The callback used to emit the node. */ function emitNodeWithSourceMap(hint, node, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { @@ -73853,7 +73935,7 @@ var ts; * @param emitCallback The callback used to emit the token. */ function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; @@ -73871,6 +73953,9 @@ var ts; } return tokenPos; } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } /** * Set the current source file. * @@ -73882,6 +73967,9 @@ var ts; } currentSource = sourceFile; currentSourceText = currentSource.text; + if (isJsonSourceMapSource(sourceFile)) { + return; + } // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location @@ -73903,7 +73991,7 @@ var ts; * Gets the text for the source map. */ function getText() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } encodeLastRecordedSourceMapSpan(); @@ -73921,7 +74009,7 @@ var ts; * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } if (compilerOptions.inlineSourceMap) { @@ -74383,7 +74471,7 @@ var ts; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; @@ -75620,7 +75708,7 @@ var ts; increaseIndent(); } var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); @@ -79434,11 +79522,9 @@ var ts; else if (ts.isLiteralImportTypeNode(node)) { imports = ts.append(imports, node.argument.literal); } - else { - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); - } + collectDynamicImportOrRequireCallsForEachChild(node); + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); } } function collectDynamicImportOrRequireCallsForEachChild(node) { @@ -81185,8 +81271,29 @@ var ts; function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } - function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { - for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; if (searchIndex === 0) { // Folder isnt at expected minimun levels @@ -81195,14 +81302,6 @@ var ts; } return true; } - function canWatchDirectory(dirPath) { - return isDirectoryAtleastAtLevelFromFSRoot(dirPath, - // When root is "/" do not watch directories like: - // "/", "/user", "/user/username", "/user/username/folderAtRoot" - // When root is "c:/" do not watch directories like: - // "c:/", "c:/folderAtRoot" - dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); - } function filterFSRootDirectoriesToWatch(watchPath, dirPath) { if (!canWatchDirectory(dirPath)) { watchPath.ignore = true; @@ -81709,11 +81808,11 @@ 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]; } + var _a; return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, @@ -83146,6 +83245,7 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + /** @internal */ function getOptionFromName(optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); @@ -83159,6 +83259,7 @@ var ts; } return optionNameMap.get(optionName); } + ts.getOptionFromName = getOptionFromName; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -85747,18 +85848,37 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { 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, preferences.quotePreference === "single") : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); } ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile) ? 0 /* Single */ : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -86122,9 +86242,9 @@ var ts; return node.forEachChild(function (child) { return child; }); } /* @internal */ - function getUniqueName(baseName, fileText) { + function getUniqueName(baseName, sourceFile) { var nameText = baseName; - for (var i = 1; ts.stringContains(fileText, nameText); i++) { + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { nameText = baseName + "_" + i; } return nameText; @@ -86145,7 +86265,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = newText.indexOf(name); + var index = indexInTextChange(newText, name); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -86162,6 +86282,17 @@ var ts; return lastPos; } ts.getRenameLocation = getRenameLocation; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -87964,7 +88095,7 @@ var ts; return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; - var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -91139,19 +91270,28 @@ var ts; } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { - var symbol = checker.getSymbolAtLocation(definition); - if (!symbol) - return true; // Be lenient with invalid code. - return getPossibleSymbolReferenceNodes(sourceFile, symbol.name).some(function (token) { - if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) - return false; - var referenceSymbol = checker.getSymbolAtLocation(token); - return referenceSymbol === symbol - || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol - || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol; - }); + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos, /*includeJsDocComment*/ true); }); @@ -91892,66 +92032,180 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - 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) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } + updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); }); } ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var canonicalPath = getCanonicalFileName(path); + if (canonicalPath === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(canonicalPath, canonicalOldPath); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + }; + } + function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var result = []; + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + var _loop_14 = function (sourceFile) { + var newImportFromPath = oldToNew(sourceFile.fileName) || sourceFile.fileName; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) + : getSourceFileToImport(importLiteral, sourceFile, program, host, oldToNew); + return toImport === undefined ? undefined : ts.moduleSpecifiers.getModuleSpecifier(program, sourceFile, newImportFromPath, toImport, host, preferences); + }); + }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations - if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } + _loop_14(sourceFile); } - return result; } - 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.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importLiteral, importingSourceFile, program, host, oldToNew) { + var symbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + if (symbol) { + if (symbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; // No need to update if it's an ambient module + var oldFileName = ts.find(symbol.declarations, ts.isSourceFile).fileName; + return oldToNew(oldFileName) || oldFileName; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, program); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, program) { + return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); + function getIfInProgram(oldLocation) { + var newLocation = oldToNew(oldLocation); + return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) + ? newLocation || oldLocation + : undefined; + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } } function createStringRange(node, sourceFile) { return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -92743,7 +92997,8 @@ var ts; } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typing, name) { - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && isTypingUpToDate(typing, typesRegistry.get(name))) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { inferredTypings.set(name, typing.typingLocation); } }); @@ -92937,7 +93192,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_15 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -92949,7 +93204,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { var sourceFile = sourceFiles_7[_i]; - _loop_14(sourceFile); + _loop_15(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -94430,13 +94685,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_16 = 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_15(start); + var state_4 = _loop_16(start); if (typeof state_4 === "object") return state_4.value; } @@ -95104,7 +95359,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -95118,7 +95373,7 @@ var ts; }; for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { var declaration = declarations_13[_b]; - var state_5 = _loop_16(declaration); + var state_5 = _loop_17(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -96273,7 +96528,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_18 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -96292,7 +96547,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_18(opt); } return options; } @@ -99064,6 +99319,12 @@ var ts; this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); if (!containingList) { @@ -99281,7 +99542,7 @@ var ts; else if (ts.isStatement(node) || ts.isClassOrTypeElement(node)) { return { suffix: this.newLineCharacter }; } - else if (ts.isVariableDeclaration(node)) { + else if (ts.isVariableDeclaration(node) || ts.isStringLiteral(node)) { return { prefix: ", " }; } else if (ts.isPropertyAssignment(node)) { @@ -99496,14 +99757,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_19 = 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_18(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -99515,7 +99776,7 @@ var ts; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); var changes = ts.formatting.formatDocument(sourceFile, formatContext); var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; @@ -100272,11 +100533,11 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); } } }); @@ -100284,7 +100545,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100294,7 +100555,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100305,14 +100566,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100347,10 +100608,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100358,7 +100619,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, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } @@ -100373,7 +100634,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100386,11 +100647,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100402,20 +100663,20 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: ts.Debug.assertNever(name); } @@ -100557,7 +100818,7 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { case 179 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -100566,7 +100827,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100577,12 +100838,12 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: ts.Debug.assertNever(name); } @@ -100591,7 +100852,7 @@ var ts; * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -100626,7 +100887,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100666,10 +100927,10 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -100918,7 +101179,7 @@ var ts; var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifierWithoutQuotes, ts.getQuotePreference(sourceFile, preferences)); var importDecl = importKind !== 3 /* Equals */ ? ts.createImportDeclaration( /*decorators*/ undefined, @@ -100939,15 +101200,6 @@ var ts; // are there are already a new line seperating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - function shouldUseSingleQuote(sourceFile, preferences) { - if (preferences.quotePreference) { - return preferences.quotePreference === "single"; - } - else { - var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); - return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); - } - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -103171,7 +103423,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103334,78 +103586,99 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + // Note: fromSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(program, fromSourceFile, fromSourceFileName, toFileName, host, preferences) { + var info = getInfo(program.getCompilerOptions(), fromSourceFile, fromSourceFileName, host); + var compilerOptions = program.getCompilerOptions(); + return getGlobalModuleSpecifier(toFileName, info, host, compilerOptions) || + ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; // For each symlink/original for a module, returns a list of ways to import that file. function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [[ambient]]; 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]; + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.fileName, host); + var modulePaths = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); + return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { + return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { + var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || compilerOptions.rootDirs && tryGetModuleNameFromRootDirs(compilerOptions.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + } + function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { + var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + 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]; + } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { @@ -103681,7 +103954,7 @@ var ts; } } function doChange(changes, sourceFile, info, preferences) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -104327,7 +104600,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; @@ -104543,7 +104816,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted variable var file = scope.getSourceFile(); - var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined @@ -104936,7 +105209,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_20 = 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 @@ -104976,7 +105249,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_20(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -105333,8 +105606,8 @@ var ts; return undefined; 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); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), @@ -105438,7 +105711,7 @@ var ts; return undefined; var startStatement = statements[startNodeIndex]; if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { - return [statements[startNodeIndex]]; + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; } // Can't only partially include the start node or be partially into the next node if (range.pos > startStatement.getStart(file)) @@ -105447,7 +105720,10 @@ var ts; // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; } function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); @@ -105457,7 +105733,7 @@ var ts; 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, preferences)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); 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. @@ -105467,10 +105743,11 @@ var ts; return undefined; var all = []; var ranges = []; - 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] }); + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); }); return all.length === 0 ? undefined : { all: all, ranges: ranges }; } @@ -105500,26 +105777,27 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { 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, preferences); + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); 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, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).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); + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -105532,11 +105810,13 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_21 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_22 = function (statement) { forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) ? ts.getPropertySymbolFromBindingElement(checker, name.parent) @@ -105548,16 +105828,68 @@ var ts; var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); }); }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_22(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_21(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 243 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 245 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 242 /* ImportEqualsDeclaration */: + return node.name; + case 231 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 243 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 242 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 231 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { @@ -105584,7 +105916,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -105595,13 +105927,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { 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, preferences); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105700,7 +106032,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105732,7 +106064,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -107147,9 +107479,9 @@ 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 _a; var syntaxTreeCache = new SyntaxTreeCache(host); var program; var lastProjectVersion; @@ -107859,8 +108191,9 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } - function getEditsForFileRename(oldFilePath, newFilePath, formatOptions) { - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions)); + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 35200473ef5..de424afca90 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -714,10 +714,14 @@ declare namespace ts { kind: SyntaxKind.ThisType; } type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionTypeNode extends TypeNode, SignatureDeclarationBase { + interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; + type: TypeNode; + } + interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.FunctionType; } - interface ConstructorTypeNode extends TypeNode, SignatureDeclarationBase { + interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.ConstructorType; } interface NodeWithTypeArguments extends TypeNode { @@ -4154,18 +4158,18 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; @@ -4564,7 +4568,7 @@ declare namespace ts { getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; - getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings): ReadonlyArray; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 7bf5c7f971d..78fc16846f8 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1635,7 +1635,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.9"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -3938,6 +3938,23 @@ var ts; return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function tryRemoveDirectoryPrefix(path, dirPath) { + var a = tryRemovePrefix(path, dirPath); + if (a === undefined) + return undefined; + switch (a.charCodeAt(0)) { + case 47 /* slash */: + case 92 /* backslash */: + return a.slice(1); + default: + return undefined; + } + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3947,6 +3964,10 @@ var ts; return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; } ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; function stringContains(str, substring) { return str.indexOf(substring) !== -1; } @@ -4106,6 +4127,7 @@ var ts; function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } + /** @param path directory of the tsconfig.json */ function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); @@ -4119,14 +4141,18 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); // Associate an array of results with each include regex. This keeps results in order of the "include" order. // If there are no "includes", then just put everything in results[0]. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; @@ -9265,11 +9291,6 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -9696,7 +9717,7 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { + return objectLiteral.properties.filter(function (property) { if (property.kind === 269 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); @@ -9712,15 +9733,18 @@ var ts; } 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; - }); + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, 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 getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -14748,7 +14772,6 @@ var ts; 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 = {})); @@ -15447,6 +15470,7 @@ var ts; 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); + sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); var pos = getNodePos(); @@ -15900,8 +15924,8 @@ var ts; kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { addJSDocComment(node); } @@ -16754,6 +16778,23 @@ var ts; } return finishNode(node); } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 161 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 162 /* FunctionType */: + case 163 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + // parameters.pos === parameters.end only if we used parseMissingList, else should contain at least `()` + return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type); + } + case 172 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); var node = createNode(160 /* TypePredicate */, lhs.pos); @@ -16924,18 +16965,20 @@ var ts; return finishNode(node); } /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. * @returns If return type parsing succeeds */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + var parametersParsedSuccessfully = parseParameterList(signature, flags); if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { signature.type = parseTypeOrTypePredicate(); - return signature.type !== undefined; + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; } - return true; + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -16953,7 +16996,8 @@ var ts; } return false; } - function parseParameterList(flags) { + // Returns true on success. + function parseParameterList(signature, flags) { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -16967,25 +17011,18 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(19 /* OpenParenToken */)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1 /* Yield */)); - setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { - // Caller insisted that we had to end with a ) We didn't. So just return - // undefined here. - return undefined; - } - return result; + if (!parseExpected(19 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; } - // We didn't even have an open paren. If the caller requires a complete parameter list, - // we definitely can't provide that. However, if they're ok with an incomplete one, - // then just return an empty set of parameters. - return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. @@ -17214,23 +17251,14 @@ var ts; var node = createNode(172 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); - if (!node.type) { - return undefined; - } parseExpected(20 /* CloseParenToken */); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163 /* ConstructorType */) { - parseExpected(94 /* NewKeyword */); - } - if (!fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */ | (sourceFile.languageVariant === 1 /* JSX */ ? 8 /* RequireCompleteParameterList */ : 0), node)) { - return undefined; - } - if (!node.parameters) { - return undefined; - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94 /* NewKeyword */) ? 163 /* ConstructorType */ : 162 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } function parseKeywordAndNoDot() { @@ -17546,11 +17574,8 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); - } - if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(163 /* ConstructorType */); + if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { @@ -17981,11 +18006,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - 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) { + if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -25076,6 +25097,9 @@ var ts; } break; case 224 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; case 222 /* ContinueStatement */: case 223 /* BreakStatement */: transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -27689,8 +27713,14 @@ var ts; break; } } + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { - break loop; + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } } break; case 237 /* EnumDeclaration */: @@ -27822,9 +27852,8 @@ var ts; 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; + location = ts.getJSDocHost(location); + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -28113,7 +28142,7 @@ var ts; : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } function isSyntacticDefault(node) { - return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */)); + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { @@ -28783,6 +28812,43 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainerOfSymbol(symbol) { + var container = getParentOfSymbol(symbol); + if (container) { + return container; + } + var candidate = ts.forEach(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!candidate) { + return undefined; + } + var alias = getAliasForSymbolInContainer(candidate, symbol); + return alias ? candidate : undefined; + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? getMergedSymbol(symbol.exportSymbol) @@ -29058,7 +29124,7 @@ var ts; // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); + symbol = getContainerOfSymbol(symbol); } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named @@ -29690,9 +29756,13 @@ var ts; context.enclosingDeclaration = undefined; if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); - if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + } } } var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); @@ -29876,12 +29946,12 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + var parent = getContainerOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); if (parent) { var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); if (parentChain) { parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); } } } @@ -34887,12 +34957,13 @@ var ts; return links.resolvedType; } function resolveImportSymbolType(node, links, symbol, meaning) { - links.resolvedSymbol = symbol; + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; if (meaning === 67216319 /* Value */) { - return links.resolvedType = getTypeOfSymbol(symbol); + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { - return links.resolvedType = getTypeReferenceType(node, symbol); + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol } } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { @@ -42757,7 +42828,7 @@ var ts; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = undefined; + typeArguments = node.typeArguments; if (node.template.kind === 201 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. @@ -43578,6 +43649,7 @@ var ts; if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { + ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc return anySignature; } if (superType !== unknownType) { @@ -45517,6 +45589,9 @@ var ts; node.contextualType = saveContextualType; return type; } + function checkExpresionNoReturn(node) { + checkExpression(node); + } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -47248,7 +47323,7 @@ var ts; function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; 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)); + addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -57597,7 +57672,7 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements) + ? ts.setTextRange(ts.createNodeArray(ts.prependStatements(statements.slice(), declarations)), statements) : ts.prependStatements(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; @@ -58925,7 +59000,8 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && - !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -60068,6 +60144,7 @@ var ts; case 165 /* TypeLiteral */: case 119 /* AnyKeyword */: case 173 /* ThisType */: + case 178 /* ImportType */: break; default: return ts.Debug.failBadSyntaxKind(node); @@ -61949,6 +62026,8 @@ var ts; return visitAwaitExpression(node); case 202 /* YieldExpression */: return visitYieldExpression(node); + case 224 /* ReturnStatement */: + return visitReturnStatement(node); case 227 /* LabeledStatement */: return visitLabeledStatement(node); case 183 /* ObjectLiteralExpression */: @@ -62008,6 +62087,12 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); + } + return ts.visitEachChild(node, visitor, context); + } function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); @@ -62184,7 +62269,7 @@ var ts; ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), + /*statement*/ convertForOfStatementHead(node, getValue)), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -64384,6 +64469,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; + var leadingStatements = []; var statements = []; var body = node.body; var statementOffset; @@ -64391,18 +64477,14 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); - // If we added any generated statements, this must be a multi-line block. - if (!multiLine && statements.length > 0) { - multiLine = true; + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -64440,10 +64522,10 @@ var ts; ts.prependStatements(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) { + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -68850,7 +68932,7 @@ var ts; name: "typescript:generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); /*@internal*/ @@ -73632,7 +73714,7 @@ var ts; * @param sourceFileOrBundle The input source file or bundle for the program. */ function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { - if (disabled) { + if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { return; } if (sourceMapData) { @@ -73755,7 +73837,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos)) { + if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { return; } if (extendedDiagnostics) { @@ -73804,7 +73886,7 @@ var ts; * @param emitCallback The callback used to emit the node. */ function emitNodeWithSourceMap(hint, node, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { @@ -73853,7 +73935,7 @@ var ts; * @param emitCallback The callback used to emit the token. */ function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; @@ -73871,6 +73953,9 @@ var ts; } return tokenPos; } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } /** * Set the current source file. * @@ -73882,6 +73967,9 @@ var ts; } currentSource = sourceFile; currentSourceText = currentSource.text; + if (isJsonSourceMapSource(sourceFile)) { + return; + } // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location @@ -73903,7 +73991,7 @@ var ts; * Gets the text for the source map. */ function getText() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } encodeLastRecordedSourceMapSpan(); @@ -73921,7 +74009,7 @@ var ts; * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { - if (disabled) { + if (disabled || isJsonSourceMapSource(currentSource)) { return; } if (compilerOptions.inlineSourceMap) { @@ -74383,7 +74471,7 @@ var ts; } else { var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error var isJs = ts.isSourceFileJavaScript(sourceFile); var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; @@ -75620,7 +75708,7 @@ var ts; increaseIndent(); } var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); @@ -79434,11 +79522,9 @@ var ts; else if (ts.isLiteralImportTypeNode(node)) { imports = ts.append(imports, node.argument.literal); } - else { - collectDynamicImportOrRequireCallsForEachChild(node); - if (ts.hasJSDocNodes(node)) { - ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); - } + collectDynamicImportOrRequireCallsForEachChild(node); + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); } } function collectDynamicImportOrRequireCallsForEachChild(node) { @@ -81185,8 +81271,29 @@ var ts; function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } - function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { - for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; if (searchIndex === 0) { // Folder isnt at expected minimun levels @@ -81195,14 +81302,6 @@ var ts; } return true; } - function canWatchDirectory(dirPath) { - return isDirectoryAtleastAtLevelFromFSRoot(dirPath, - // When root is "/" do not watch directories like: - // "/", "/user", "/user/username", "/user/username/folderAtRoot" - // When root is "c:/" do not watch directories like: - // "c:/", "c:/folderAtRoot" - dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); - } function filterFSRootDirectoriesToWatch(watchPath, dirPath) { if (!canWatchDirectory(dirPath)) { watchPath.ignore = true; @@ -81709,11 +81808,11 @@ 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]; } + var _a; return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, @@ -83146,6 +83245,7 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + /** @internal */ function getOptionFromName(optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); @@ -83159,6 +83259,7 @@ var ts; } return optionNameMap.get(optionName); } + ts.getOptionFromName = getOptionFromName; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -85747,18 +85848,37 @@ var ts; return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } ts.hostGetCanonicalFileName = hostGetCanonicalFileName; - function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, preferences) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, preferences) : undefined; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; } ts.makeImportIfNecessary = makeImportIfNecessary; - function makeImport(defaultImport, namedImports, moduleSpecifier, preferences) { + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { 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, preferences.quotePreference === "single") : moduleSpecifier); + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); } ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); + return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile) ? 0 /* Single */ : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; function symbolNameNoDefault(symbol) { var escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); @@ -86122,9 +86242,9 @@ var ts; return node.forEachChild(function (child) { return child; }); } /* @internal */ - function getUniqueName(baseName, fileText) { + function getUniqueName(baseName, sourceFile) { var nameText = baseName; - for (var i = 1; ts.stringContains(fileText, nameText); i++) { + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { nameText = baseName + "_" + i; } return nameText; @@ -86145,7 +86265,7 @@ var ts; for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { var change = textChanges_1[_b]; var span = change.span, newText = change.newText; - var index = newText.indexOf(name); + var index = indexInTextChange(newText, name); if (index !== -1) { lastPos = span.start + delta + index; // If the reference comes first, return immediately. @@ -86162,6 +86282,17 @@ var ts; return lastPos; } ts.getRenameLocation = getRenameLocation; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -87964,7 +88095,7 @@ var ts; return { codeActions: undefined, sourceDisplay: undefined }; } var moduleSymbol = symbolOriginInfo.moduleSymbol; - var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -91139,19 +91270,28 @@ var ts; } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { - var symbol = checker.getSymbolAtLocation(definition); - if (!symbol) - return true; // Be lenient with invalid code. - return getPossibleSymbolReferenceNodes(sourceFile, symbol.name).some(function (token) { - if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) - return false; - var referenceSymbol = checker.getSymbolAtLocation(token); - return referenceSymbol === symbol - || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol - || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol; - }); + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos, /*includeJsDocComment*/ true); }); @@ -91892,66 +92032,180 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFilePath, newFilePath, host, formatContext) { - var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host); + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { - updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath); - 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) { - var range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile); - changeTracker.replaceRangeWithText(sourceFile, range, isRef(toUpdate) ? newPath : ts.removeFileExtension(newPath)); - } - } + updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); }); } ts.getEditsForFileRename = getEditsForFileRename; - function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) { + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var canonicalPath = getCanonicalFileName(path); + if (canonicalPath === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(canonicalPath, canonicalOldPath); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + }; + } + function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { var configFile = program.getCompilerOptions().configFile; - var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath); - if (oldFile) { - changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath); + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function isRef(toUpdate) { - return "fileName" in toUpdate; - } - function getImportsToUpdate(program, oldFilePath, host) { - var result = []; + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + var _loop_14 = function (sourceFile) { + var newImportFromPath = oldToNew(sourceFile.fileName) || sourceFile.fileName; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, program) + : getSourceFileToImport(importLiteral, sourceFile, program, host, oldToNew); + return toImport === undefined ? undefined : ts.moduleSpecifiers.getModuleSpecifier(program, sourceFile, newImportFromPath, toImport, host, preferences); + }); + }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var ref = _c[_b]; - if (ts.resolveTripleslashReference(ref.fileName, sourceFile.fileName) === oldFilePath) { - result.push({ sourceFile: sourceFile, toUpdate: ref }); - } - } - for (var _d = 0, _e = sourceFile.imports; _d < _e.length; _d++) { - var importStringLiteral = _e[_d]; - var resolved = host.resolveModuleNames - ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName) - : program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName); - // We may or may not have picked up on the file being renamed, so maybe successfully resolved to oldFilePath, or maybe that's in failedLookupLocations - if (resolved && ts.contains(resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : resolved.failedLookupLocations, oldFilePath)) { - result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral }); - } - } + _loop_14(sourceFile); } - return result; } - 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.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host))); - return function (oldPath) { - if (!ts.pathIsRelative(oldPath)) - return; - return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel))); - }; + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importLiteral, importingSourceFile, program, host, oldToNew) { + var symbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + if (symbol) { + if (symbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; // No need to update if it's an ambient module + var oldFileName = ts.find(symbol.declarations, ts.isSourceFile).fileName; + return oldToNew(oldFileName) || oldFileName; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, program); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, program) { + return resolved && ((resolved.resolvedModule && getIfInProgram(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfInProgram)); + function getIfInProgram(oldLocation) { + var newLocation = oldToNew(oldLocation); + return program.getSourceFile(oldLocation) || newLocation !== undefined && program.getSourceFile(newLocation) + ? newLocation || oldLocation + : undefined; + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } } function createStringRange(node, sourceFile) { return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -92743,7 +92997,8 @@ var ts; } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typing, name) { - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && isTypingUpToDate(typing, typesRegistry.get(name))) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { inferredTypings.set(name, typing.typingLocation); } }); @@ -92937,7 +93192,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_15 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -92949,7 +93204,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { var sourceFile = sourceFiles_7[_i]; - _loop_14(sourceFile); + _loop_15(sourceFile); } rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { @@ -94430,13 +94685,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_16 = 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_15(start); + var state_4 = _loop_16(start); if (typeof state_4 === "object") return state_4.value; } @@ -95104,7 +95359,7 @@ var ts; var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - var _loop_16 = function (declaration) { + var _loop_17 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -95118,7 +95373,7 @@ var ts; }; for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) { var declaration = declarations_13[_b]; - var state_5 = _loop_16(declaration); + var state_5 = _loop_17(declaration); if (typeof state_5 === "object") return state_5.value; } @@ -96273,7 +96528,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_18 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -96292,7 +96547,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_18(opt); } return options; } @@ -99064,6 +99319,12 @@ var ts; this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + }; ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); if (!containingList) { @@ -99281,7 +99542,7 @@ var ts; else if (ts.isStatement(node) || ts.isClassOrTypeElement(node)) { return { suffix: this.newLineCharacter }; } - else if (ts.isVariableDeclaration(node)) { + else if (ts.isVariableDeclaration(node) || ts.isStringLiteral(node)) { return { prefix: ", " }; } else if (ts.isPropertyAssignment(node)) { @@ -99496,14 +99757,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_19 = 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_18(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -99515,7 +99776,7 @@ var ts; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); var changes = ts.formatting.formatDocument(sourceFile, formatContext); var text = applyChanges(nonFormattedText, changes); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; @@ -100272,11 +100533,11 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, preferences); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes, preferences); + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); } } }); @@ -100284,7 +100545,7 @@ var ts; return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes, preferences) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); @@ -100294,7 +100555,7 @@ var ts; var importNode = ts.importFromModuleSpecifier(moduleSpecifier); switch (importNode.kind) { case 242 /* ImportEqualsDeclaration */: - changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, preferences)); + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; case 186 /* CallExpression */: if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { @@ -100305,14 +100566,14 @@ var ts; } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target, preferences) { + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -100347,10 +100608,10 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, preferences) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { case 213 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences); + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; case 215 /* ExpressionStatement */: { var expression = statement.expression; @@ -100358,7 +100619,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, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], preferences)); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } @@ -100373,7 +100634,7 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, preferences) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { @@ -100386,11 +100647,11 @@ var ts; } else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, preferences); + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); } else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, preferences); + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); } } // Move it out to its own variable statement. (This will not be used if `!foundImport`) @@ -100402,20 +100663,20 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, preferences) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { case 179 /* ObjectBindingPattern */: case 180 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier, preferences), + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier, preferences)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: ts.Debug.assertNever(name); } @@ -100557,7 +100818,7 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, preferences) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { case 179 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { @@ -100566,7 +100827,7 @@ var ts; : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { - return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, preferences)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration @@ -100577,12 +100838,12 @@ var ts; */ var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, preferences), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: ts.Debug.assertNever(name); } @@ -100591,7 +100852,7 @@ var ts; * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, preferences) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -100626,7 +100887,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, preferences)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -100666,10 +100927,10 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier, preferences) { + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" - ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, preferences) - : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, preferences); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); } function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); @@ -100918,7 +101179,7 @@ var ts; var sourceFile = context.sourceFile, symbolName = context.symbolName, preferences = context.preferences; var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = ts.createLiteral(moduleSpecifierWithoutQuotes, shouldUseSingleQuote(sourceFile, preferences)); + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifierWithoutQuotes, ts.getQuotePreference(sourceFile, preferences)); var importDecl = importKind !== 3 /* Equals */ ? ts.createImportDeclaration( /*decorators*/ undefined, @@ -100939,15 +101200,6 @@ var ts; // are there are already a new line seperating code and import statements. return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); } - function shouldUseSingleQuote(sourceFile, preferences) { - if (preferences.quotePreference) { - return preferences.quotePreference === "single"; - } - else { - var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); - return !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); - } - } function createImportClauseOfKind(kind, symbolName) { var id = ts.createIdentifier(symbolName); switch (kind) { @@ -103171,7 +103423,7 @@ var ts; var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, context.preferences))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -103334,78 +103586,99 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + // Note: fromSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(program, fromSourceFile, fromSourceFileName, toFileName, host, preferences) { + var info = getInfo(program.getCompilerOptions(), fromSourceFile, fromSourceFileName, host); + var compilerOptions = program.getCompilerOptions(); + return getGlobalModuleSpecifier(toFileName, info, host, compilerOptions) || + ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; // For each symlink/original for a module, returns a list of ways to import that file. function getModuleSpecifiers(moduleSymbol, program, importingSourceFile, host, preferences) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [[ambient]]; 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]; + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.fileName, host); + var modulePaths = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); + return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { + return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { + var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory) + || compilerOptions.rootDirs && tryGetModuleNameFromRootDirs(compilerOptions.rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); + } + function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { + var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; + 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]; + } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { @@ -103681,7 +103954,7 @@ var ts; } } function doChange(changes, sourceFile, info, preferences) { - changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, preferences)); + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -104327,7 +104600,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; @@ -104543,7 +104816,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted variable var file = scope.getSourceFile(); - var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined @@ -104936,7 +105209,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_19 = function (i) { + var _loop_20 = 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 @@ -104976,7 +105249,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_19(i); + _loop_20(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -105333,8 +105606,8 @@ var ts; return undefined; 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); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), @@ -105438,7 +105711,7 @@ var ts; return undefined; var startStatement = statements[startNodeIndex]; if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { - return [statements[startNodeIndex]]; + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; } // Can't only partially include the start node or be partially into the next node if (range.pos > startStatement.getStart(file)) @@ -105447,7 +105720,10 @@ var ts; // Can't be partially into the next node if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) return undefined; - return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex); + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; } function doChange(oldFile, program, toMove, changes, host, preferences) { var checker = program.getTypeChecker(); @@ -105457,7 +105733,7 @@ var ts; 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, preferences)); + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); 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. @@ -105467,10 +105743,11 @@ var ts; return undefined; var all = []; var ranges = []; - 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] }); + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); }); return all.length === 0 ? undefined : { all: all, ranges: ranges }; } @@ -105500,26 +105777,27 @@ var ts; changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); } } - function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { 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, preferences); + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); 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, preferences).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).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); + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); } } function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { @@ -105532,11 +105810,13 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_20 = function (sourceFile) { + var _loop_21 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_21 = function (statement) { + var _loop_22 = function (statement) { forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; var shouldMove = function (name) { var symbol = ts.isBindingElement(name.parent) ? ts.getPropertySymbolFromBindingElement(checker, name.parent) @@ -105548,16 +105828,68 @@ var ts; var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); }); }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_21(statement); + _loop_22(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_20(sourceFile); + _loop_21(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 243 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 245 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 242 /* ImportEqualsDeclaration */: + return node.name; + case 231 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 243 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 242 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 231 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); } } function moduleSpecifierFromImport(i) { @@ -105584,7 +105916,7 @@ var ts; } } } - function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, preferences) { + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { var defaultImport; var imports = []; newFileNeedExport.forEach(function (symbol) { @@ -105595,13 +105927,13 @@ var ts; imports.push(symbol.name); } }); - return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, preferences); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); } - function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, preferences) { + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { 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, preferences); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); } else { ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. @@ -105700,7 +106032,7 @@ var ts; break; } } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, preferences) { + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { var copiedOldImports = []; for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { var oldStatement = _a[_i]; @@ -105732,7 +106064,7 @@ var ts; } } }); - ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, preferences)); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); return copiedOldImports; } function makeUniqueModuleName(moduleName, extension, inDirectory, host) { @@ -107147,9 +107479,9 @@ 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 _a; var syntaxTreeCache = new SyntaxTreeCache(host); var program; var lastProjectVersion; @@ -107859,8 +108191,9 @@ var ts; var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } - function getEditsForFileRename(oldFilePath, newFilePath, formatOptions) { - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions)); + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.defaultPreferences; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 36608eae4c7..a262a7e5dea 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -180,7 +180,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.9"; - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -2130,6 +2130,23 @@ var ts; return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function tryRemoveDirectoryPrefix(path, dirPath) { + var a = tryRemovePrefix(path, dirPath); + if (a === undefined) + return undefined; + switch (a.charCodeAt(0)) { + case 47: + case 92: + return a.slice(1); + default: + return undefined; + } + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -2139,6 +2156,10 @@ var ts; return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; } ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; function stringContains(str, substring) { return str.indexOf(substring) !== -1; } @@ -2278,14 +2299,17 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; @@ -5237,11 +5261,6 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; function createDiagnosticForNodeFromMessageChain(node, messageChain) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); @@ -5632,7 +5651,7 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { + return objectLiteral.properties.filter(function (property) { if (property.kind === 269) { var propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); @@ -5648,15 +5667,18 @@ var ts; } 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; - }); + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, 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 getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { return ts.findAncestor(node.parent, ts.isFunctionLike); } @@ -12292,6 +12314,7 @@ var ts; if (languageVersion === void 0) { languageVersion = 2; } initializeState(sourceText, languageVersion, syntaxCursor, 6); sourceFile = createSourceFile(fileName, 2, 6, false); + sourceFile.flags = contextFlags; nextToken(); var pos = getNodePos(); if (token() === 1) { @@ -12672,8 +12695,8 @@ var ts; kind === 71 ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2) { addJSDocComment(node); } @@ -13340,6 +13363,21 @@ var ts; } return finishNode(node); } + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 161: + return ts.nodeIsMissing(node.typeName); + case 162: + case 163: { + var _a = node, parameters = _a.parameters, type = _a.type; + return parameters.pos === parameters.end || typeHasArrowFunctionBlockingParseError(type); + } + case 172: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); var node = createNode(160, lhs.pos); @@ -13482,12 +13520,13 @@ var ts; if (!(flags & 32)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); + var parametersParsedSuccessfully = parseParameterList(signature, flags); if (shouldParseReturnType(returnToken, !!(flags & 4))) { signature.type = parseTypeOrTypePredicate(); - return signature.type !== undefined; + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; } - return true; + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36) { @@ -13504,21 +13543,19 @@ var ts; } return false; } - function parseParameterList(flags) { - if (parseExpected(19)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1)); - setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20) && (flags & 8)) { - return undefined; - } - return result; + function parseParameterList(signature, flags) { + if (!parseExpected(19)) { + signature.parameters = createMissingList(); + return false; } - return (flags & 8) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + signature.parameters = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20); } function parseTypeMemberSemicolon() { if (parseOptional(26)) { @@ -13709,23 +13746,14 @@ var ts; var node = createNode(172); parseExpected(19); node.type = parseType(); - if (!node.type) { - return undefined; - } parseExpected(20); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163) { - parseExpected(94); - } - if (!fillSignature(36, 4 | (sourceFile.languageVariant === 1 ? 8 : 0), node)) { - return undefined; - } - if (!node.parameters) { - return undefined; - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94) ? 163 : 162; + var node = createNodeWithJSDoc(kind, pos); + fillSignature(36, 4, node); return finishNode(node); } function parseKeywordAndNoDot() { @@ -14024,11 +14052,8 @@ var ts; return doOutsideOfContext(20480, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162); - } - if (token() === 94) { - return parseFunctionOrConstructorType(163); + if (isStartOfFunctionType() || token() === 94) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85)) { @@ -14325,10 +14350,7 @@ var ts; var node = createNodeWithJSDoc(192); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256) ? 2 : 0; - if (!fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node)) { - return undefined; - } - if (!node.parameters) { + if (!fillSignature(56, isAsync, node) && !allowAmbiguity) { return undefined; } if (!allowAmbiguity && token() !== 36 && token() !== 17) { @@ -18305,6 +18327,7 @@ var ts; } return optionNameMap.get(optionName); } + ts.getOptionFromName = getOptionFromName; function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { var configFileText; try { @@ -20373,7 +20396,8 @@ var ts; addInferredTypings(module_1, "Inferred typings from unresolved imports"); } packageNameToTypingLocation.forEach(function (typing, name) { - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && isTypingUpToDate(typing, typesRegistry.get(name))) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { inferredTypings.set(name, typing.typingLocation); } }); @@ -20631,6 +20655,7 @@ var ts; this.pendingRunRequests = []; this.installRunCount = 1; this.inFlightRequestCount = 0; + this.latestDistTag = "latest"; this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames); this.globalCacheCanonicalPackageJsonPath = ts.combinePaths(this.toCanonicalFileName(globalCachePath), "package.json"); if (this.log.isEnabled()) { @@ -20848,7 +20873,7 @@ var ts; continue; } var distTags = _this.typesRegistry.get(packageName); - var newVersion = ts.Semver.parse(distTags["ts" + ts.versionMajorMinor] || distTags[latestDistTag]); + var newVersion = ts.Semver.parse(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); var newTyping = { typingLocation: typingFile, version: newVersion }; _this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); @@ -21007,7 +21032,6 @@ var ts; return "@types/" + packageName + "@ts" + ts.versionMajorMinor; } typingsInstaller.typingsName = typingsName; - var latestDistTag = "latest"; })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -21086,7 +21110,7 @@ var ts; if (_this.log.isEnabled()) { _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package..."); } - _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName, { cwd: globalTypingsCacheLocation }); + _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation }); if (_this.log.isEnabled()) { _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package"); }