From a6decf98bffabcfb50f928ce10f00ea9e2d66206 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 13 Dec 2016 14:53:19 -0800 Subject: [PATCH] Update LKG --- lib/lib.es2016.array.include.d.ts | 9 + lib/protocol.d.ts | 31 + lib/tsc.js | 438 +++++++----- lib/tsserver.js | 1055 ++++++++++++++++++----------- lib/tsserverlibrary.d.ts | 96 ++- lib/tsserverlibrary.js | 1010 ++++++++++++++++----------- lib/typescript.d.ts | 20 +- lib/typescript.js | 625 ++++++++++------- lib/typescriptServices.d.ts | 20 +- lib/typescriptServices.js | 625 ++++++++++------- lib/typingsInstaller.js | 49 +- 11 files changed, 2487 insertions(+), 1491 deletions(-) diff --git a/lib/lib.es2016.array.include.d.ts b/lib/lib.es2016.array.include.d.ts index 42b95c478d0..9a557068eaa 100644 --- a/lib/lib.es2016.array.include.d.ts +++ b/lib/lib.es2016.array.include.d.ts @@ -27,6 +27,15 @@ interface Array { includes(searchElement: T, fromIndex?: number): boolean; } +interface ReadonlyArray { + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + interface Int8Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 63d79603503..21bd96653f8 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -711,6 +711,10 @@ declare namespace ts.server.protocol { * List of removed files */ removed: string[]; + /** + * List of updated files + */ + updated: string[]; } /** * Information found in a configure request. @@ -729,6 +733,10 @@ declare namespace ts.server.protocol { * The format options to use during formatting and other code editing features. */ formatOptions?: FormatCodeSettings; + /** + * The host's additional supported file extensions + */ + extraFileExtensions?: FileExtensionInfo[]; } /** * Configure request; value of command field is "configure". Specifies @@ -957,6 +965,10 @@ declare namespace ts.server.protocol { * Documentation associated with symbol. */ documentation: string; + /** + * JSDoc tags associated with symbol. + */ + tags: JSDocTagInfo[]; } /** * Quickinfo response message. @@ -1158,6 +1170,10 @@ declare namespace ts.server.protocol { * Documentation strings for the symbol. */ documentation: SymbolDisplayPart[]; + /** + * JSDoc tags for the symbol. + */ + tags: JSDocTagInfo[]; } interface CompletionsResponse extends Response { body?: CompletionEntry[]; @@ -1214,6 +1230,10 @@ declare namespace ts.server.protocol { * The signature's documentation */ documentation: SymbolDisplayPart[]; + /** + * The signature's JSDoc tags + */ + tags: JSDocTagInfo[]; } /** * Signature help items found in the response of a signature help request. @@ -1846,6 +1866,17 @@ declare namespace ts.server.protocol { [option: string]: string[] | boolean | undefined; } + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } + + interface JSDocTagInfo { + name: string; + text?: string; + } + interface MapLike { [index: string]: T; } diff --git a/lib/tsc.js b/lib/tsc.js index fabf59f75bd..2b29bb12042 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -132,7 +132,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.1.4"; + ts.version = "2.1.5"; })(ts || (ts = {})); (function (ts) { var createObject = Object.create; @@ -813,15 +813,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -1668,8 +1659,19 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -1680,11 +1682,11 @@ var ts; return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions) { + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -3202,6 +3204,7 @@ var ts; JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, @@ -4801,6 +4804,7 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, writeLine: function () { return str_1 += " "; }, increaseIndent: ts.noop, @@ -5435,6 +5439,18 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 162) { + return node.elementType; + } + else if (node && node.kind === 157) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { @@ -6051,6 +6067,7 @@ var ts; cache = ts.concatenate(cache, node.jsDoc); } } + ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { if (!isParameter(param)) { return undefined; @@ -7406,39 +7423,6 @@ var ts; } return output; } - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - function stringifyFallback(value) { - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -15688,7 +15672,7 @@ var ts; break; case 38: var asterisk = scanner.getTokenText(); - if (state === 1) { + if (state === 1 || state === 2) { state = 2; pushComment(asterisk); } @@ -15703,7 +15687,10 @@ var ts; break; case 5: var whitespace = scanner.getTokenText(); - if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -15711,6 +15698,7 @@ var ts; case 1: break; default: + state = 2; pushComment(scanner.getTokenText()); break; } @@ -15800,7 +15788,7 @@ var ts; } function parseTagComments(indent) { var comments = []; - var state = 1; + var state = 0; var margin; function pushComment(text) { if (!margin) { @@ -20565,9 +20553,8 @@ var ts; } if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { - ts.Debug.assert(!!moduleNotFoundError); var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleName, resolvedModule.resolvedFileName); + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (compilerOptions.noImplicitAny && moduleNotFoundError) { error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); @@ -20796,6 +20783,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { return true; @@ -20809,26 +20806,28 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -21550,7 +21549,7 @@ var ts; } ts.Debug.assert(bindingElement.kind === 174); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 55); writeSpace(writer); } @@ -22165,16 +22164,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -22286,10 +22276,27 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216) { return getTypeOfInstantiatedSymbol(symbol); @@ -23060,8 +23067,8 @@ var ts; setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); var typeParameter = getTypeParameterFromMappedType(type); var constraintType = getConstraintTypeFromMappedType(type); - var homomorphicType = getHomomorphicTypeFromMappedType(type); var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getModifiersTypeFromMappedType(type); var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; @@ -23072,11 +23079,11 @@ var ts; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { var propName = t.text; - var homomorphicProp = homomorphicType && getPropertyOfType(homomorphicType, propName); - var isOptional = templateOptional || !!(homomorphicProp && homomorphicProp.flags & 536870912); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); prop.type = propType; - prop.isReadonly = templateReadonly || homomorphicProp && isReadonlySymbol(homomorphicProp); + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); members[propName] = prop; } else if (t.flags & 2) { @@ -23099,9 +23106,20 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : unknownType); } - function getHomomorphicTypeFromMappedType(type) { - var constraint = getConstraintDeclaration(getTypeParameterFromMappedType(type)); - return constraint.kind === 168 ? instantiateType(getTypeFromTypeNode(constraint.type), type.mapper || identityMapper) : undefined; + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; } function getErasedTemplateTypeFromMappedType(type) { return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); @@ -23183,23 +23201,18 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } - function getApparentTypeOfIndexedAccess(type) { - return getIndexTypeOfType(getApparentType(type.objectType), 0) || type; - } function getApparentType(type) { - var t = type.flags & 16384 ? getApparentTypeOfTypeParameter(type) : - type.flags & 524288 ? getApparentTypeOfIndexedAccess(type) : - type; + var t = type.flags & 540672 ? getApparentTypeOfTypeVariable(type) : type; return t.flags & 262178 ? globalStringType : t.flags & 340 ? globalNumberType : t.flags & 136 ? globalBooleanType : @@ -23694,6 +23707,11 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143).parent); } @@ -24237,6 +24255,17 @@ var ts; var type = createType(524288); type.objectType = objectType; type.indexType = indexType; + if (type.objectType.flags & 229376) { + type.constraint = getIndexTypeOfType(type.objectType, 0); + } + else if (type.objectType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0); + } + } return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { @@ -24312,7 +24341,9 @@ var ts; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || isGenericMappedType(objectType)) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 178) || + isGenericMappedType(objectType)) { if (objectType.flags & 1) { return objectType; } @@ -25234,6 +25265,23 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; if (source.flags & 96 && source.flags & 1048576) { @@ -25256,7 +25304,7 @@ var ts; } return 0; } - if (target.flags & 196608) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } @@ -25287,7 +25335,7 @@ var ts; return result; } } - if (target.flags & 16384) { + else if (target.flags & 16384) { if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); @@ -25312,8 +25360,8 @@ var ts; return result; } } - if (target.type.flags & 16384) { - var constraint = getConstraintOfTypeParameter(target.type); + if (target.type.flags & 540672) { + var constraint = getConstraintOfTypeVariable(target.type); if (constraint) { if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { return result; @@ -25327,12 +25375,19 @@ var ts; return result; } } + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } if (source.flags & 16384) { if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } @@ -25349,6 +25404,14 @@ var ts; } } } + else if (source.flags & 524288) { + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } else { if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { @@ -27876,18 +27939,21 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; if (container.kind === 150) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } if (container.kind === 185) { container = ts.getThisContainer(container, false); @@ -28001,6 +28067,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } @@ -28456,7 +28525,7 @@ var ts; return mapper && mapper.context; } function checkSpreadExpression(node, contextualMapper) { - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { @@ -28671,8 +28740,10 @@ var ts; if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), true); } - spread.flags |= propagatedFlags; - spread.symbol = node.symbol; + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } return spread; } return createObjectLiteralType(); @@ -29955,12 +30026,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8) { @@ -31119,8 +31191,8 @@ var ts; } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); if (apparentType.flags & (2 | 4 | 8 | 16)) { return true; } @@ -31775,7 +31847,7 @@ var ts; checkSourceElement(node.type); var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - var keyType = constraintType.flags & 16384 ? getApparentTypeOfTypeParameter(constraintType) : constraintType; + var keyType = constraintType.flags & 540672 ? getApparentTypeOfTypeVariable(constraintType) : constraintType; checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { @@ -32064,7 +32136,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -32200,6 +32272,9 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; + } function checkDecorators(node) { if (!node.decorators) { return; @@ -32223,7 +32298,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -32232,11 +32307,13 @@ var ts; case 152: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markTypeNodeAsReferenced(node.type); break; case 147: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; case 144: markTypeNodeAsReferenced(node.type); break; @@ -32367,6 +32444,13 @@ var ts; } } } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } function errorUnusedLocal(node, name) { if (isIdentifierThatStartsWithUnderScore(node)) { var declaration = ts.getRootDeclaration(node.parent); @@ -32376,7 +32460,9 @@ var ts; return; } } - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -33295,7 +33381,7 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (languageVersion < 2) { + if (languageVersion < 2 && !ts.isInAmbientContext(node)) { checkExternalEmitHelpers(baseTypeNode.parent, 1); } var baseTypes = getBaseTypes(type); @@ -37952,10 +38038,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -37980,14 +38067,14 @@ var ts; } return { decorators: decorators }; } - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } function addClassElementDecorationStatements(statements, node, isStatic) { @@ -38012,7 +38099,7 @@ var ts; } function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -38035,7 +38122,7 @@ var ts; } function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -38063,35 +38150,35 @@ var ts; } return expressions; } - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeReturnTypeOfNode(node)))); @@ -38112,12 +38199,16 @@ var ts; return node.kind === 149; } function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 226 - || kind === 197 - || kind === 149 - || kind === 151 - || kind === 152; + switch (node.kind) { + case 226: + case 197: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149: + case 151: + case 152: + return true; + } + return false; } function serializeTypeOfNode(node) { switch (node.kind) { @@ -38135,18 +38226,7 @@ var ts; return ts.createVoidZero(); } } - function getRestParameterElementType(node) { - if (node && node.kind === 162) { - return node.elementType; - } - else if (node && node.kind === 157) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -38154,7 +38234,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -38162,7 +38242,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -38171,6 +38251,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } function serializeReturnTypeOfNode(node) { if (ts.isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); @@ -41068,12 +41157,17 @@ var ts; convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } + startLexicalEnvironment(); var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); var currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { + if (loopOutParameters.length || lexicalEnvironment) { var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1, statements_4); + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, undefined, true); } if (!ts.isBlock(loopBody)) { @@ -43379,11 +43473,11 @@ var ts; ], undefined, moduleBodyBlock); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); - var updated = ts.updateSourceFileNode(node, ts.createNodeArray([ + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) - ], node.statements)); + ], node.statements)), 1024); if (!(compilerOptions.outFile || compilerOptions.out)) { ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } @@ -45205,7 +45299,7 @@ var ts; return; } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, @@ -45371,6 +45465,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -45642,6 +45739,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -50917,14 +51015,7 @@ var ts; } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -51164,9 +51255,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -51289,7 +51381,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -51393,7 +51485,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -51405,7 +51497,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; diff --git a/lib/tsserver.js b/lib/tsserver.js index dba897cfe9b..a8b7d330940 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -137,7 +137,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.1.4"; + ts.version = "2.1.5"; })(ts || (ts = {})); (function (ts) { var createObject = Object.create; @@ -818,15 +818,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -1673,8 +1664,19 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -1685,11 +1687,11 @@ var ts; return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions) { + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -3207,6 +3209,7 @@ var ts; JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, @@ -5291,14 +5294,7 @@ var ts; } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -5538,9 +5534,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -5663,7 +5660,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -5767,7 +5764,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -5779,7 +5776,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; @@ -6897,6 +6894,7 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, writeLine: function () { return str_1 += " "; }, increaseIndent: ts.noop, @@ -7531,6 +7529,18 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 162) { + return node.elementType; + } + else if (node && node.kind === 157) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { @@ -8147,6 +8157,7 @@ var ts; cache = ts.concatenate(cache, node.jsDoc); } } + ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { if (!isParameter(param)) { return undefined; @@ -9502,39 +9513,6 @@ var ts; } return output; } - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - function stringifyFallback(value) { - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -17784,7 +17762,7 @@ var ts; break; case 38: var asterisk = scanner.getTokenText(); - if (state === 1) { + if (state === 1 || state === 2) { state = 2; pushComment(asterisk); } @@ -17799,7 +17777,10 @@ var ts; break; case 5: var whitespace = scanner.getTokenText(); - if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -17807,6 +17788,7 @@ var ts; case 1: break; default: + state = 2; pushComment(scanner.getTokenText()); break; } @@ -17896,7 +17878,7 @@ var ts; } function parseTagComments(indent) { var comments = []; - var state = 1; + var state = 0; var margin; function pushComment(text) { if (!margin) { @@ -22079,9 +22061,8 @@ var ts; } if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { - ts.Debug.assert(!!moduleNotFoundError); var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleName, resolvedModule.resolvedFileName); + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (compilerOptions.noImplicitAny && moduleNotFoundError) { error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); @@ -22310,6 +22291,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { return true; @@ -22323,26 +22314,28 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -23064,7 +23057,7 @@ var ts; } ts.Debug.assert(bindingElement.kind === 174); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 55); writeSpace(writer); } @@ -23679,16 +23672,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -23800,10 +23784,27 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216) { return getTypeOfInstantiatedSymbol(symbol); @@ -24574,8 +24575,8 @@ var ts; setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); var typeParameter = getTypeParameterFromMappedType(type); var constraintType = getConstraintTypeFromMappedType(type); - var homomorphicType = getHomomorphicTypeFromMappedType(type); var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getModifiersTypeFromMappedType(type); var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; @@ -24586,11 +24587,11 @@ var ts; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { var propName = t.text; - var homomorphicProp = homomorphicType && getPropertyOfType(homomorphicType, propName); - var isOptional = templateOptional || !!(homomorphicProp && homomorphicProp.flags & 536870912); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); prop.type = propType; - prop.isReadonly = templateReadonly || homomorphicProp && isReadonlySymbol(homomorphicProp); + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); members[propName] = prop; } else if (t.flags & 2) { @@ -24613,9 +24614,20 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : unknownType); } - function getHomomorphicTypeFromMappedType(type) { - var constraint = getConstraintDeclaration(getTypeParameterFromMappedType(type)); - return constraint.kind === 168 ? instantiateType(getTypeFromTypeNode(constraint.type), type.mapper || identityMapper) : undefined; + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; } function getErasedTemplateTypeFromMappedType(type) { return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); @@ -24697,23 +24709,18 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } - function getApparentTypeOfIndexedAccess(type) { - return getIndexTypeOfType(getApparentType(type.objectType), 0) || type; - } function getApparentType(type) { - var t = type.flags & 16384 ? getApparentTypeOfTypeParameter(type) : - type.flags & 524288 ? getApparentTypeOfIndexedAccess(type) : - type; + var t = type.flags & 540672 ? getApparentTypeOfTypeVariable(type) : type; return t.flags & 262178 ? globalStringType : t.flags & 340 ? globalNumberType : t.flags & 136 ? globalBooleanType : @@ -25208,6 +25215,11 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143).parent); } @@ -25751,6 +25763,17 @@ var ts; var type = createType(524288); type.objectType = objectType; type.indexType = indexType; + if (type.objectType.flags & 229376) { + type.constraint = getIndexTypeOfType(type.objectType, 0); + } + else if (type.objectType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0); + } + } return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { @@ -25826,7 +25849,9 @@ var ts; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || isGenericMappedType(objectType)) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 178) || + isGenericMappedType(objectType)) { if (objectType.flags & 1) { return objectType; } @@ -26748,6 +26773,23 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; if (source.flags & 96 && source.flags & 1048576) { @@ -26770,7 +26812,7 @@ var ts; } return 0; } - if (target.flags & 196608) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } @@ -26801,7 +26843,7 @@ var ts; return result; } } - if (target.flags & 16384) { + else if (target.flags & 16384) { if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); @@ -26826,8 +26868,8 @@ var ts; return result; } } - if (target.type.flags & 16384) { - var constraint = getConstraintOfTypeParameter(target.type); + if (target.type.flags & 540672) { + var constraint = getConstraintOfTypeVariable(target.type); if (constraint) { if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { return result; @@ -26841,12 +26883,19 @@ var ts; return result; } } + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } if (source.flags & 16384) { if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } @@ -26863,6 +26912,14 @@ var ts; } } } + else if (source.flags & 524288) { + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } else { if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { @@ -29390,18 +29447,21 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; if (container.kind === 150) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } if (container.kind === 185) { container = ts.getThisContainer(container, false); @@ -29515,6 +29575,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } @@ -29970,7 +30033,7 @@ var ts; return mapper && mapper.context; } function checkSpreadExpression(node, contextualMapper) { - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { @@ -30185,8 +30248,10 @@ var ts; if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), true); } - spread.flags |= propagatedFlags; - spread.symbol = node.symbol; + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } return spread; } return createObjectLiteralType(); @@ -31469,12 +31534,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8) { @@ -32633,8 +32699,8 @@ var ts; } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); if (apparentType.flags & (2 | 4 | 8 | 16)) { return true; } @@ -33289,7 +33355,7 @@ var ts; checkSourceElement(node.type); var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - var keyType = constraintType.flags & 16384 ? getApparentTypeOfTypeParameter(constraintType) : constraintType; + var keyType = constraintType.flags & 540672 ? getApparentTypeOfTypeVariable(constraintType) : constraintType; checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { @@ -33578,7 +33644,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -33714,6 +33780,9 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; + } function checkDecorators(node) { if (!node.decorators) { return; @@ -33737,7 +33806,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -33746,11 +33815,13 @@ var ts; case 152: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markTypeNodeAsReferenced(node.type); break; case 147: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; case 144: markTypeNodeAsReferenced(node.type); break; @@ -33881,6 +33952,13 @@ var ts; } } } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } function errorUnusedLocal(node, name) { if (isIdentifierThatStartsWithUnderScore(node)) { var declaration = ts.getRootDeclaration(node.parent); @@ -33890,7 +33968,9 @@ var ts; return; } } - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -34809,7 +34889,7 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (languageVersion < 2) { + if (languageVersion < 2 && !ts.isInAmbientContext(node)) { checkExternalEmitHelpers(baseTypeNode.parent, 1); } var baseTypes = getBaseTypes(type); @@ -39466,10 +39546,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -39494,14 +39575,14 @@ var ts; } return { decorators: decorators }; } - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } function addClassElementDecorationStatements(statements, node, isStatic) { @@ -39526,7 +39607,7 @@ var ts; } function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -39549,7 +39630,7 @@ var ts; } function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -39577,35 +39658,35 @@ var ts; } return expressions; } - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeReturnTypeOfNode(node)))); @@ -39626,12 +39707,16 @@ var ts; return node.kind === 149; } function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 226 - || kind === 197 - || kind === 149 - || kind === 151 - || kind === 152; + switch (node.kind) { + case 226: + case 197: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149: + case 151: + case 152: + return true; + } + return false; } function serializeTypeOfNode(node) { switch (node.kind) { @@ -39649,18 +39734,7 @@ var ts; return ts.createVoidZero(); } } - function getRestParameterElementType(node) { - if (node && node.kind === 162) { - return node.elementType; - } - else if (node && node.kind === 157) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -39668,7 +39742,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -39676,7 +39750,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -39685,6 +39759,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } function serializeReturnTypeOfNode(node) { if (ts.isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); @@ -42582,12 +42665,17 @@ var ts; convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } + startLexicalEnvironment(); var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); var currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { + if (loopOutParameters.length || lexicalEnvironment) { var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1, statements_4); + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, undefined, true); } if (!ts.isBlock(loopBody)) { @@ -45456,11 +45544,11 @@ var ts; ], undefined, moduleBodyBlock); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); - var updated = ts.updateSourceFileNode(node, ts.createNodeArray([ + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) - ], node.statements)); + ], node.statements)), 1024); if (!(compilerOptions.outFile || compilerOptions.out)) { ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } @@ -46623,6 +46711,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -48232,7 +48321,7 @@ var ts; return; } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, @@ -48398,6 +48487,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -51926,7 +52018,9 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; @@ -52997,6 +53091,7 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -55010,13 +55105,14 @@ var ts; var symbols = completionData.symbols, location_3 = completionData.location; var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), kind: symbolKind, displayParts: displayParts, - documentation: documentation + documentation: documentation, + tags: tags }; } } @@ -55027,7 +55123,8 @@ var ts; kind: ts.ScriptElementKind.keyword, kindModifiers: ts.ScriptElementKindModifier.none, displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined + documentation: undefined, + tags: undefined }; } return undefined; @@ -57591,6 +57688,29 @@ var ts; return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getJsDocTagsFromDeclarations(declarations) { + var tags = []; + forEachUnique(declarations, function (declaration) { + var jsDocs = ts.getJSDocs(declaration); + if (!jsDocs) { + return; + } + for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { + var doc = jsDocs_1[_i]; + var tagsForDoc = doc.tags; + if (tagsForDoc) { + tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 279; }).map(function (jsDocTag) { + return { + name: jsDocTag.tagName.text, + text: jsDocTag.comment + }; + })); + } + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; function forEachUnique(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -57649,13 +57769,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 70 ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } var preamble = "/**" + newLine + indentationStr + " * "; @@ -59577,7 +59703,8 @@ var ts; suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: [ts.punctuationPart(25), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment() + documentation: candidateSignature.getDocumentationComment(), + tags: candidateSignature.getJsDocTags() }; }); var argumentIndex = argumentListInfo.argumentIndex; @@ -59714,6 +59841,7 @@ var ts; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; + var tags; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; @@ -59994,6 +60122,7 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); + tags = symbol.getJsDocTags(); if (documentation.length === 0 && symbol.flags & 4) { if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 261; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -60006,6 +60135,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(); + tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; } @@ -60013,7 +60143,7 @@ var ts; } } } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; function addNewLineIfDisplayPartsExist() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -60064,6 +60194,7 @@ var ts; displayParts.push(ts.punctuationPart(19)); } documentation = signature.getDocumentationComment(); + tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { @@ -62902,6 +63033,12 @@ var ts; } return this.documentationComment; }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; return SymbolObject; }()); var TokenObject = (function (_super) { @@ -62985,6 +63122,12 @@ var ts; } return this.documentationComment; }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; return SignatureObject; }()); var SourceFileObject = (function (_super) { @@ -63588,7 +63731,8 @@ var ts; kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined + documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } } @@ -63600,7 +63744,8 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation + documentation: displayPartsDocumentationsAndKind.documentation, + tags: displayPartsDocumentationsAndKind.tags }; } function getDefinitionAtPosition(fileName, position) { @@ -63886,7 +64031,7 @@ var ts; return false; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { @@ -64065,22 +64210,160 @@ var ts; (function (ts) { var server; (function (server) { + var TextStorage = (function () { + function TextStorage(host, fileName) { + this.host = host; + this.fileName = fileName; + this.svcVersion = 0; + this.textVersion = 0; + } + TextStorage.prototype.getVersion = function () { + return this.svc + ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshot().version + : "Text-" + this.textVersion; + }; + TextStorage.prototype.hasScriptVersionCache = function () { + return this.svc !== undefined; + }; + TextStorage.prototype.useScriptVersionCache = function (newText) { + this.switchToScriptVersionCache(newText); + }; + TextStorage.prototype.useText = function (newText) { + this.svc = undefined; + this.setText(newText); + }; + TextStorage.prototype.edit = function (start, end, newText) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + }; + TextStorage.prototype.reload = function (text) { + if (this.svc) { + this.svc.reload(text); + } + else { + this.setText(text); + } + }; + TextStorage.prototype.reloadFromFile = function (tempFileName) { + if (this.svc || (tempFileName !== this.fileName)) { + this.reload(this.getFileText(tempFileName)); + } + else { + this.setText(undefined); + } + }; + TextStorage.prototype.getSnapshot = function () { + return this.svc + ? this.svc.getSnapshot() + : ts.ScriptSnapshot.fromString(this.getOrLoadText()); + }; + TextStorage.prototype.getLineInfo = function (line) { + return this.switchToScriptVersionCache().getSnapshot().index.lineNumberToInfo(line); + }; + TextStorage.prototype.lineToTextSpan = function (line) { + if (!this.svc) { + var lineMap = this.getLineMap(); + var start = lineMap[line]; + var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return ts.createTextSpanFromBounds(start, end); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + if (!this.svc) { + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + TextStorage.prototype.positionToLineOffset = function (position) { + if (!this.svc) { + var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + var index = this.svc.getSnapshot().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + TextStorage.prototype.getFileText = function (tempFileName) { + return this.host.readFile(tempFileName || this.fileName) || ""; + }; + TextStorage.prototype.ensureNoScriptVersionCache = function () { + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + }; + TextStorage.prototype.switchToScriptVersionCache = function (newText) { + if (!this.svc) { + this.svc = server.ScriptVersionCache.fromString(this.host, newText !== undefined ? newText : this.getOrLoadText()); + this.svcVersion++; + this.text = undefined; + } + return this.svc; + }; + TextStorage.prototype.getOrLoadText = function () { + this.ensureNoScriptVersionCache(); + if (this.text === undefined) { + this.setText(this.getFileText()); + } + return this.text; + }; + TextStorage.prototype.getLineMap = function () { + this.ensureNoScriptVersionCache(); + return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); + }; + TextStorage.prototype.setText = function (newText) { + this.ensureNoScriptVersionCache(); + if (newText === undefined || this.text !== newText) { + this.text = newText; + this.lineMap = undefined; + this.textVersion++; + } + }; + return TextStorage; + }()); + server.TextStorage = TextStorage; var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { - if (isOpen === void 0) { isOpen = false; } + function ScriptInfo(host, fileName, scriptKind, hasMixedContent) { if (hasMixedContent === void 0) { hasMixedContent = false; } this.host = host; this.fileName = fileName; this.scriptKind = scriptKind; - this.isOpen = isOpen; this.hasMixedContent = hasMixedContent; this.containingProjects = []; this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = server.ScriptVersionCache.fromString(host, content); + this.textStorage = new TextStorage(host, fileName); + if (hasMixedContent) { + this.textStorage.reload(""); + } this.scriptKind = scriptKind ? scriptKind : ts.getScriptKindFromFileName(fileName); } + ScriptInfo.prototype.isScriptOpen = function () { + return this.isOpen; + }; + ScriptInfo.prototype.open = function (newText) { + this.isOpen = true; + this.textStorage.useScriptVersionCache(newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.close = function () { + this.isOpen = false; + this.textStorage.useText(this.hasMixedContent ? "" : undefined); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.getSnapshot = function () { + return this.textStorage.getSnapshot(); + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatCodeSettings; }; @@ -64134,6 +64417,12 @@ var ts; } return this.containingProjects[0]; }; + ScriptInfo.prototype.registerFileUpdate = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.registerFileUpdate(this.path); + } + }; ScriptInfo.prototype.setFormatOptions = function (formatSettings) { if (formatSettings) { if (!this.formatCodeSettings) { @@ -64153,14 +64442,14 @@ var ts; } }; ScriptInfo.prototype.getLatestVersion = function () { - return this.svc.latestVersion().toString(); + return this.textStorage.getVersion(); }; ScriptInfo.prototype.reload = function (script) { - this.svc.reload(script); + this.textStorage.reload(script); this.markContainingProjectsAsDirty(); }; ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.snap(); + var snap = this.textStorage.getSnapshot(); this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; ScriptInfo.prototype.reloadFromFile = function (tempFileName) { @@ -64168,19 +64457,15 @@ var ts; this.reload(""); } else { - this.svc.reloadFromFile(tempFileName || this.fileName); + this.textStorage.reloadFromFile(tempFileName); this.markContainingProjectsAsDirty(); } }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); + return this.textStorage.getLineInfo(line); }; ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); + this.textStorage.edit(start, end, newText); this.markContainingProjectsAsDirty(); }; ScriptInfo.prototype.markContainingProjectsAsDirty = function () { @@ -64190,27 +64475,13 @@ var ts; } }; ScriptInfo.prototype.lineToTextSpan = function (line) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); + return this.textStorage.lineToTextSpan(line); }; ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); + return this.textStorage.lineOffsetToPosition(line, offset); }; ScriptInfo.prototype.positionToLineOffset = function (position) { - var index = this.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return this.textStorage.positionToLineOffset(position); }; return ScriptInfo; }()); @@ -64339,7 +64610,7 @@ var ts; LSHost.prototype.getScriptSnapshot = function (filename) { var scriptInfo = this.project.getScriptInfoLSHost(filename); if (scriptInfo) { - return scriptInfo.snap(); + return scriptInfo.getSnapshot(); } }; LSHost.prototype.getScriptFileNames = function () { @@ -64555,10 +64826,15 @@ var ts; function AbstractBuilder(project, ctor) { this.project = project; this.ctor = ctor; - this.fileInfos = ts.createFileMap(); } + AbstractBuilder.prototype.getFileInfos = function () { + return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createFileMap()); + }; + AbstractBuilder.prototype.clear = function () { + this.fileInfos_doNotAccessDirectly = undefined; + }; AbstractBuilder.prototype.getFileInfo = function (path) { - return this.fileInfos.get(path); + return this.getFileInfos().get(path); }; AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { var fileInfo = this.getFileInfo(path); @@ -64570,16 +64846,16 @@ var ts; return fileInfo; }; AbstractBuilder.prototype.getFileInfoPaths = function () { - return this.fileInfos.getKeys(); + return this.getFileInfos().getKeys(); }; AbstractBuilder.prototype.setFileInfo = function (path, info) { - this.fileInfos.set(path, info); + this.getFileInfos().set(path, info); }; AbstractBuilder.prototype.removeFileInfo = function (path) { - this.fileInfos.remove(path); + this.getFileInfos().remove(path); }; AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.fileInfos.forEachValue(function (_path, value) { return action(value); }); + this.getFileInfos().forEachValue(function (_path, value) { return action(value); }); }; AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { var fileInfo = this.getFileInfo(scriptInfo.path); @@ -64681,6 +64957,10 @@ var ts; _this.project = project; return _this; } + ModuleBuilder.prototype.clear = function () { + this.projectVersionForDependencyGraph = undefined; + _super.prototype.clear.call(this); + }; ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { var _this = this; if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { @@ -64877,107 +65157,6 @@ var ts; return UnresolvedImportsMap; }()); server.UnresolvedImportsMap = UnresolvedImportsMap; - var emptyResult = []; - var getEmptyResult = function () { return emptyResult; }; - var getUndefined = function () { return undefined; }; - var emptyEncodedSemanticClassifications = { spans: emptyResult, endOfLineState: 0 }; - function createNoSemanticFeaturesWrapper(realLanguageService) { - return { - cleanupSemanticCache: ts.noop, - getSyntacticDiagnostics: function (fileName) { - return fileName ? realLanguageService.getSyntacticDiagnostics(fileName) : emptyResult; - }, - getSemanticDiagnostics: getEmptyResult, - getCompilerOptionsDiagnostics: function () { - return realLanguageService.getCompilerOptionsDiagnostics(); - }, - getSyntacticClassifications: function (fileName, span) { - return realLanguageService.getSyntacticClassifications(fileName, span); - }, - getEncodedSyntacticClassifications: function (fileName, span) { - return realLanguageService.getEncodedSyntacticClassifications(fileName, span); - }, - getSemanticClassifications: getEmptyResult, - getEncodedSemanticClassifications: function () { - return emptyEncodedSemanticClassifications; - }, - getCompletionsAtPosition: getUndefined, - findReferences: getEmptyResult, - getCompletionEntryDetails: getUndefined, - getQuickInfoAtPosition: getUndefined, - findRenameLocations: getEmptyResult, - getNameOrDottedNameSpan: function (fileName, startPos, endPos) { - return realLanguageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - }, - getBreakpointStatementAtPosition: function (fileName, position) { - return realLanguageService.getBreakpointStatementAtPosition(fileName, position); - }, - getBraceMatchingAtPosition: function (fileName, position) { - return realLanguageService.getBraceMatchingAtPosition(fileName, position); - }, - getSignatureHelpItems: getUndefined, - getDefinitionAtPosition: getEmptyResult, - getRenameInfo: function () { return ({ - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(ts.Diagnostics.Language_service_is_disabled), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }); }, - getTypeDefinitionAtPosition: getUndefined, - getReferencesAtPosition: getEmptyResult, - getDocumentHighlights: getEmptyResult, - getOccurrencesAtPosition: getEmptyResult, - getNavigateToItems: getEmptyResult, - getNavigationBarItems: function (fileName) { - return realLanguageService.getNavigationBarItems(fileName); - }, - getNavigationTree: function (fileName) { - return realLanguageService.getNavigationTree(fileName); - }, - getOutliningSpans: function (fileName) { - return realLanguageService.getOutliningSpans(fileName); - }, - getTodoComments: getEmptyResult, - getIndentationAtPosition: function (fileName, position, options) { - return realLanguageService.getIndentationAtPosition(fileName, position, options); - }, - getFormattingEditsForRange: function (fileName, start, end, options) { - return realLanguageService.getFormattingEditsForRange(fileName, start, end, options); - }, - getFormattingEditsForDocument: function (fileName, options) { - return realLanguageService.getFormattingEditsForDocument(fileName, options); - }, - getFormattingEditsAfterKeystroke: function (fileName, position, key, options) { - return realLanguageService.getFormattingEditsAfterKeystroke(fileName, position, key, options); - }, - getDocCommentTemplateAtPosition: function (fileName, position) { - return realLanguageService.getDocCommentTemplateAtPosition(fileName, position); - }, - isValidBraceCompletionAtPosition: function (fileName, position, openingBrace) { - return realLanguageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); - }, - getEmitOutput: getUndefined, - getProgram: function () { - return realLanguageService.getProgram(); - }, - getNonBoundSourceFile: function (fileName) { - return realLanguageService.getNonBoundSourceFile(fileName); - }, - dispose: function () { - return realLanguageService.dispose(); - }, - getCompletionEntrySymbol: getUndefined, - getImplementationAtPosition: getEmptyResult, - getSourceFile: function (fileName) { - return realLanguageService.getSourceFile(fileName); - }, - getCodeFixesAtPosition: getEmptyResult - }; - } - server.createNoSemanticFeaturesWrapper = createNoSemanticFeaturesWrapper; var Project = (function () { function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { this.projectName = projectName; @@ -65006,7 +65185,6 @@ var ts; this.lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); this.lsHost.setCompilationSettings(this.compilerOptions); this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry); - this.noSemanticFeaturesLanguageService = createNoSemanticFeaturesWrapper(this.languageService); if (!languageServiceEnabled) { this.disableLanguageService(); } @@ -65037,9 +65215,7 @@ var ts; if (ensureSynchronized) { this.updateGraph(); } - return this.languageServiceEnabled - ? this.languageService - : this.noSemanticFeaturesLanguageService; + return this.languageService; }; Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { if (!this.languageServiceEnabled) { @@ -65113,7 +65289,9 @@ var ts; if (this.rootFiles) { for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { var f = _a[_i]; - result.push(f.fileName); + if (this.languageServiceEnabled || f.isScriptOpen()) { + result.push(f.fileName); + } } if (this.typingFiles) { for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { @@ -65129,6 +65307,9 @@ var ts; }; Project.prototype.getScriptInfos = function () { var _this = this; + if (!this.languageServiceEnabled) { + return this.rootFiles; + } return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { @@ -65187,7 +65368,7 @@ var ts; }; Project.prototype.containsFile = function (filename, requireOpen) { var info = this.projectService.getScriptInfoForNormalizedPath(filename); - if (info && (info.isOpen || !requireOpen)) { + if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } }; @@ -65212,6 +65393,9 @@ var ts; } this.markAsDirty(); }; + Project.prototype.registerFileUpdate = function (fileName) { + (this.updatedFileNames || (this.updatedFileNames = ts.createMap()))[fileName] = fileName; + }; Project.prototype.markAsDirty = function () { this.projectStateVersion++; }; @@ -65244,9 +65428,6 @@ var ts; this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); }; Project.prototype.updateGraph = function () { - if (!this.languageServiceEnabled) { - return true; - } this.lsHost.startRecordingFilesWithChangedResolutions(); var hasChanges = this.updateGraphWorker(); var changedFiles = this.lsHost.finishRecordingFilesWithChangedResolutions() || server.emptyArray; @@ -65268,6 +65449,12 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } + if (this.languageServiceEnabled) { + this.builder.onProjectUpdateGraph(); + } + else { + this.builder.clear(); + } if (hasChanges) { this.projectStructureVersion++; } @@ -65300,7 +65487,6 @@ var ts; } } } - this.builder.onProjectUpdateGraph(); return hasChanges; }; Project.prototype.getScriptInfoLSHost = function (fileName) { @@ -65362,16 +65548,20 @@ var ts; projectName: this.getProjectName(), version: this.projectStructureVersion, isInferred: this.projectKind === ProjectKind.Inferred, - options: this.getCompilerOptions() + options: this.getCompilerOptions(), + languageServiceDisabled: !this.languageServiceEnabled }; + var updatedFileNames = this.updatedFileNames; + this.updatedFileNames = undefined; if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { - if (this.projectStructureVersion == this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) { return { info: info, projectErrors: this.projectErrors }; } var lastReportedFileNames = this.lastReportedFileNames; var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); var added = []; var removed = []; + var updated = ts.getOwnKeys(updatedFileNames); for (var id in currentFiles) { if (!ts.hasProperty(lastReportedFileNames, id)) { added.push(id); @@ -65384,7 +65574,7 @@ var ts; } this.lastReportedFileNames = currentFiles; this.lastReportedVersion = this.projectStructureVersion; - return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; + return { info: info, changes: { added: added, removed: removed, updated: updated }, projectErrors: this.projectErrors }; } else { var projectFileNames = this.getFileNames(); @@ -65710,7 +65900,10 @@ var ts; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (_) { return undefined; }, - hasMixedContent: function (_) { return false; } + hasMixedContent: function (fileName, extraFileExtensions) { + var mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, function (item) { return item.isMixedContent; }), function (item) { return item.extension; }); + return ts.forEach(mixedContentExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, @@ -65790,7 +65983,8 @@ var ts; this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), - hostInfo: "Unknown host" + hostInfo: "Unknown host", + extraFileExtensions: [] }; this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); } @@ -65916,7 +66110,7 @@ var ts; this.handleDeletedFile(info); } else { - if (info && (!info.isOpen)) { + if (info && (!info.isScriptOpen())) { info.reloadFromFile(); this.updateProjectGraphs(info.containingProjects); } @@ -65925,7 +66119,7 @@ var ts; ProjectService.prototype.handleDeletedFile = function (info) { this.logger.info(info.fileName + " deleted"); info.stopWatcher(); - if (!info.isOpen) { + if (!info.isScriptOpen()) { this.filenameToScriptInfo.remove(info.path); this.lastDeletedFile = info; var containingProjects = info.containingProjects.slice(); @@ -65956,7 +66150,7 @@ var ts; }; ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { var _this = this; - if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) { return; } this.logger.info("Detected source file changes: " + fileName); @@ -66055,13 +66249,15 @@ var ts; } }; ProjectService.prototype.closeOpenFile = function (info) { - info.reloadFromFile(); + info.close(); server.removeItemFromSet(this.openFiles, info); - info.isOpen = false; var projectsToRemove; for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; if (p.projectKind === server.ProjectKind.Configured) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } if (p.deleteOpenRef() === 0) { (projectsToRemove || (projectsToRemove = [])).push(p); } @@ -66069,6 +66265,9 @@ var ts; else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { (projectsToRemove || (projectsToRemove = [])).push(p); } + if (!p.languageServiceEnabled) { + p.markAsDirty(); + } } if (projectsToRemove) { for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { @@ -66186,7 +66385,7 @@ var ts; config = sanitizedConfig; errors = diagnostics.length ? diagnostics : [result.error]; } - var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { errors = ts.concatenate(errors, parsedCommandLine.errors); } @@ -66265,7 +66464,7 @@ var ts; var f = files_4[_i]; var rootFilename = propertyReader.getFileName(f); var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); if (this.host.fileExists(rootFilename)) { var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); project.addRoot(info); @@ -66309,7 +66508,7 @@ var ts; rootFilesChanged = true; if (!scriptInfo) { var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); } } @@ -66340,7 +66539,7 @@ var ts; if (toAdd) { for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { var f = toAdd_1[_d]; - if (f.isOpen && isRootFileInInferredProject(f)) { + if (f.isScriptOpen() && isRootFileInInferredProject(f)) { var inferredProject = f.containingProjects[0]; inferredProject.removeFile(f); if (!inferredProject.hasRoots()) { @@ -66379,9 +66578,7 @@ var ts; project.stopWatchingDirectory(); } else { - if (!project.languageServiceEnabled) { - project.enableLanguageService(); - } + project.enableLanguageService(); this.watchConfigDirectoryForProject(project, projectOptions); this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors); } @@ -66411,29 +66608,30 @@ var ts; var _this = this; var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); + if (openedByClient || this.host.fileExists(fileName)) { + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent); this.filenameToScriptInfo.set(info.path, info); - if (!info.isOpen && !hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + if (openedByClient) { + if (fileContent === undefined) { + fileContent = this.host.readFile(fileName) || ""; + } + } + else { + if (!hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } } } } if (info) { - if (fileContent !== undefined) { - info.reload(fileContent); + if (openedByClient && !info.isScriptOpen()) { + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } } - if (openedByClient) { - info.isOpen = true; + else if (fileContent !== undefined) { + info.reload(fileContent); } } return info; @@ -66461,6 +66659,10 @@ var ts; server.mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); this.logger.info("Format host information updated"); } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.logger.info("Host file extension mappings updated"); + } } }; ProjectService.prototype.closeLog = function () { @@ -66508,19 +66710,28 @@ var ts; return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { - var _a = this.findContainingExternalProject(fileName) - ? {} - : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; + var configFileName; + var configFileErrors; + var project = this.findContainingExternalProject(fileName); + if (!project) { + (_a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + } + } + if (project && !project.languageServiceEnabled) { + project.markAsDirty(); + } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); this.assignScriptInfoToInferredProjectIfNecessary(info, true); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; + var _a; }; ProjectService.prototype.closeClientFile = function (uncheckedFileName) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); if (info) { this.closeOpenFile(info); - info.isOpen = false; } this.printProjects(); }; @@ -66547,7 +66758,7 @@ var ts; for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { var file = openFiles_1[_i]; var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen()); var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); } @@ -66614,7 +66825,23 @@ var ts; } } }; - ProjectService.prototype.openExternalProject = function (proj) { + ProjectService.prototype.openExternalProjects = function (projects) { + var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); + for (var externalProjectName in this.externalProjectToConfiguredProjectMap) { + projectsToClose[externalProjectName] = true; + } + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var externalProject = projects_4[_i]; + this.openExternalProject(externalProject, true); + delete projectsToClose[externalProject.projectFileName]; + } + for (var externalProjectName in projectsToClose) { + this.closeExternalProject(externalProjectName, true); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.openExternalProject = function (proj, suppressRefreshOfInferredProjects) { + if (suppressRefreshOfInferredProjects === void 0) { suppressRefreshOfInferredProjects = false; } if (proj.typingOptions && !proj.typeAcquisition) { var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); proj.typeAcquisition = typeAcquisition; @@ -66640,7 +66867,14 @@ var ts; var exisingConfigFiles; if (externalProject) { if (!tsConfigFiles) { - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typeAcquisition, proj.options.compileOnSave, undefined); + var compilerOptions = convertCompilerOptions(proj.options); + if (this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, proj.rootFiles, externalFilePropertyReader)) { + externalProject.disableLanguageService(); + } + else { + externalProject.enableLanguageService(); + } + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, undefined); return; } this.closeExternalProject(proj.projectFileName, true); @@ -66692,7 +66926,9 @@ var ts; delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); } - this.refreshInferredProjects(); + if (!suppressRefreshOfInferredProjects) { + this.refreshInferredProjects(); + } }; return ProjectService; }()); @@ -66854,14 +67090,11 @@ var ts; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, _a[CommandNames.OpenExternalProject] = function (request) { - _this.projectService.openExternalProject(request.arguments); + _this.projectService.openExternalProject(request.arguments, false); return _this.requiredResponse(true); }, _a[CommandNames.OpenExternalProjects] = function (request) { - for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { - var proj = _a[_i]; - _this.projectService.openExternalProject(proj); - } + _this.projectService.openExternalProjects(request.arguments.projects); return _this.requiredResponse(true); }, _a[CommandNames.CloseExternalProject] = function (request) { @@ -67258,8 +67491,8 @@ var ts; return; } this.logger.info("cleaning " + caption); - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var p = projects_4[_i]; + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var p = projects_5[_i]; p.getLanguageService(false).cleanupSemanticCache(); } }; @@ -67555,7 +67788,7 @@ var ts; var displayString = ts.displayPartsToString(nameInfo.displayParts); var nameSpan = nameInfo.textSpan; var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; - var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); var refs = server.combineProjectOutput(projects, function (project) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { @@ -67565,7 +67798,7 @@ var ts; var refScriptInfo = project.getScriptInfo(ref.fileName); var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); - var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + var lineText = refScriptInfo.getSnapshot().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); return { file: ref.fileName, start: start, @@ -67676,6 +67909,7 @@ var ts; end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), displayString: displayString, documentation: docString, + tags: quickInfo.tags || [] }; } else { @@ -67815,6 +68049,9 @@ var ts; if (!project) { server.Errors.ThrowNoProject(); } + if (!project.languageServiceEnabled) { + return false; + } var scriptInfo = project.getScriptInfo(file); return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); }; @@ -68080,7 +68317,7 @@ var ts; highPriorityFiles.push(fileNameInProject); else { var info = this.projectService.getScriptInfo(fileNameInProject); - if (!info.isOpen) { + if (!info.isScriptOpen()) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else @@ -68537,8 +68774,9 @@ var ts; } }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { - var oldSnap = oldSnapshot; - return this.getTextChangeRangeSinceVersion(oldSnap.version); + if (oldSnapshot instanceof LineIndexSnapshot) { + return this.getTextChangeRangeSinceVersion(oldSnapshot.version); + } }; return LineIndexSnapshot; }()); @@ -69022,33 +69260,40 @@ var ts; var childProcess = require("child_process"); var os = require("os"); function getGlobalTypingsCacheLocation() { - var basePath; switch (process.platform) { - case "win32": - basePath = process.env.LOCALAPPDATA || + case "win32": { + var basePath = process.env.LOCALAPPDATA || process.env.APPDATA || (os.homedir && os.homedir()) || process.env.USERPROFILE || (process.env.HOMEDRIVE && process.env.HOMEPATH && ts.normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) || os.tmpdir(); - break; - case "linux": - case "android": - basePath = (os.homedir && os.homedir()) || - process.env.HOME || - ((process.env.LOGNAME || process.env.USER) && "/home/" + (process.env.LOGNAME || process.env.USER)) || - os.tmpdir(); - break; + return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"); + } case "darwin": - var homeDir = (os.homedir && os.homedir()) || - process.env.HOME || - ((process.env.LOGNAME || process.env.USER) && "/Users/" + (process.env.LOGNAME || process.env.USER)) || - os.tmpdir(); - basePath = ts.combinePaths(homeDir, "Library/Application Support/"); - break; + case "linux": + case "android": { + var cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin"); + return ts.combinePaths(cacheLocation, "typescript"); + } + default: + ts.Debug.fail("unsupported platform '" + process.platform + "'"); + return; } - ts.Debug.assert(basePath !== undefined); - return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"); + } + function getNonWindowsCacheLocation(platformIsDarwin) { + if (process.env.XDG_CACHE_HOME) { + return process.env.XDG_CACHE_HOME; + } + var usersDir = platformIsDarwin ? "Users" : "home"; + var homePath = (os.homedir && os.homedir()) || + process.env.HOME || + ((process.env.LOGNAME || process.env.USER) && "/" + usersDir + "/" + (process.env.LOGNAME || process.env.USER)) || + os.tmpdir(); + var cacheFolder = platformIsDarwin + ? "Library/Caches" + : ".cache"; + return ts.combinePaths(ts.normalizeSlashes(homePath), cacheFolder); } var readline = require("readline"); var fs = require("fs"); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index de491bc7e3c..fcefbf779d1 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -330,10 +330,12 @@ declare namespace ts.server.protocol { isInferred: boolean; version: number; options: ts.CompilerOptions; + languageServiceDisabled: boolean; } interface ProjectChanges { added: string[]; removed: string[]; + updated: string[]; } interface ProjectFiles { info?: ProjectVersionInfo; @@ -351,6 +353,7 @@ declare namespace ts.server.protocol { hostInfo?: string; file?: string; formatOptions?: FormatCodeSettings; + extraFileExtensions?: FileExtensionInfo[]; } interface ConfigureRequest extends Request { command: CommandTypes.Configure; @@ -448,6 +451,7 @@ declare namespace ts.server.protocol { end: Location; displayString: string; documentation: string; + tags: JSDocTagInfo[]; } interface QuickInfoResponse extends Response { body?: QuickInfoResponseBody; @@ -520,6 +524,7 @@ declare namespace ts.server.protocol { kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface CompletionsResponse extends Response { body?: CompletionEntry[]; @@ -540,6 +545,7 @@ declare namespace ts.server.protocol { separatorDisplayParts: SymbolDisplayPart[]; parameters: SignatureHelpParameter[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface SignatureHelpItems { items: SignatureHelpItem[]; @@ -2517,6 +2523,7 @@ declare namespace ts { writeSpace(text: string): void; writeStringLiteral(text: string): void; writeParameter(text: string): void; + writeProperty(text: string): void; writeSymbol(text: string, symbol: Symbol): void; writeLine(): void; increaseIndent(): void; @@ -2907,6 +2914,7 @@ declare namespace ts { typeParameter?: TypeParameter; constraintType?: Type; templateType?: Type; + modifiersType?: Type; mapper?: TypeMapper; } interface EvolvingArrayType extends ObjectType { @@ -2929,18 +2937,19 @@ declare namespace ts { iteratorElementType?: Type; } interface TypeVariable extends Type { + resolvedApparentType: Type; resolvedIndexType: IndexType; } interface TypeParameter extends TypeVariable { constraint: Type; target?: TypeParameter; mapper?: TypeMapper; - resolvedApparentType: Type; isThisType?: boolean; } interface IndexedAccessType extends TypeVariable { objectType: Type; indexType: Type; + constraint?: Type; } interface IndexType extends Type { type: TypeVariable | UnionOrIntersectionType; @@ -3002,6 +3011,11 @@ declare namespace ts { PrototypeProperty = 3, ThisProperty = 4, } + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -3573,7 +3587,7 @@ declare namespace ts.performance { function disable(): void; } declare namespace ts { - const version = "2.1.4"; + const version = "2.1.5"; } declare namespace ts { const enum Ternary { @@ -3645,7 +3659,6 @@ declare namespace ts { function assign, T2>(t: T1, arg1: T2): T1 & T2; function assign>(t: T1, ...args: any[]): any; function reduceProperties(map: Map, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; - function reduceOwnProperties(map: MapLike, callback: (aggregate: U, value: T, key: string) => U, initial: U): U; function equalOwnProperties(left: MapLike, right: MapLike, equalityComparer?: (left: T, right: T) => boolean): boolean; function arrayToMap(array: T[], makeKey: (value: T) => string): Map; function arrayToMap(array: T[], makeKey: (value: T) => string, makeValue: (value: T) => U): Map; @@ -3724,10 +3737,10 @@ declare namespace ts { const supportedTypeScriptExtensions: string[]; const supportedTypescriptExtensionsForExtractExtension: string[]; const supportedJavascriptExtensions: string[]; - function getSupportedExtensions(options?: CompilerOptions): string[]; + function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[]; function hasJavaScriptFileExtension(fileName: string): boolean; function hasTypeScriptFileExtension(fileName: string): boolean; - function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; + function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): boolean; const enum ExtensionPriority { TypeScriptFiles = 0, DeclarationAndJavaScriptFiles = 2, @@ -8572,6 +8585,12 @@ declare namespace ts { key: string; message: string; }; + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Circularity_detected_while_resolving_configuration_Colon_0: { code: number; category: DiagnosticCategory; @@ -8762,7 +8781,7 @@ declare namespace ts { function generateTSConfig(options: CompilerOptions, fileNames: string[]): { compilerOptions: Map; }; - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; @@ -8974,6 +8993,7 @@ declare namespace ts { function isPartOfTypeNode(node: Node): boolean; function forEachReturnStatement(body: Block, visitor: (stmt: ReturnStatement) => T): T; function forEachYieldExpression(body: Block, visitor: (expr: YieldExpression) => void): void; + function getRestParameterElementType(node: TypeNode): TypeNode; function isVariableLike(node: Node): node is VariableLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; function isClassLike(node: Node): node is ClassLikeDeclaration; @@ -9017,6 +9037,7 @@ declare namespace ts { function hasQuestionToken(node: Node): boolean; function isJSDocConstructSignature(node: Node): boolean; function getCommentsFromJSDoc(node: Node): string[]; + function getJSDocs(node: Node): (JSDoc | JSDocTag)[]; function getJSDocParameterTags(param: Node): JSDocParameterTag[]; function getJSDocType(node: Node): JSDocType; function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag; @@ -9159,7 +9180,6 @@ declare namespace ts { function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; function tryExtractTypeScriptExtension(fileName: string): string | undefined; - const stringify: (value: any) => string; function convertToBase64(input: string): string; function getNewLineCharacter(options: CompilerOptions): string; function isSimpleExpression(node: Expression): boolean; @@ -9792,6 +9812,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[]; getDocumentationComment(): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -9812,6 +9833,7 @@ declare namespace ts { getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; } interface SourceFile { version: string; @@ -10096,12 +10118,17 @@ declare namespace ts { text: string; kind: string; } + interface JSDocTagInfo { + name: string; + text?: string; + } interface QuickInfo { kind: string; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface RenameInfo { canRename: boolean; @@ -10125,6 +10152,7 @@ declare namespace ts { separatorDisplayParts: SymbolDisplayPart[]; parameters: SignatureHelpParameter[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface SignatureHelpItems { items: SignatureHelpItem[]; @@ -10152,6 +10180,7 @@ declare namespace ts { kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface OutliningSpan { textSpan: TextSpan; @@ -10451,6 +10480,7 @@ declare namespace ts.GoToImplementation { } declare namespace ts.JsDoc { function getJsDocCommentsFromDeclarations(declarations: Declaration[]): SymbolDisplayPart[]; + function getJsDocTagsFromDeclarations(declarations: Declaration[]): JSDocTagInfo[]; function getAllJsDocCompletionEntries(): CompletionEntry[]; function getDocCommentTemplateAtPosition(newLine: string, sourceFile: SourceFile, position: number): TextInsertion; } @@ -10515,6 +10545,7 @@ declare namespace ts.SymbolDisplay { displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; symbolKind: string; + tags: JSDocTagInfo[]; }; } declare namespace ts { @@ -10979,24 +11010,57 @@ declare namespace ts { function getDefaultLibFilePath(options: CompilerOptions): string; } declare namespace ts.server { + class TextStorage { + private readonly host; + private readonly fileName; + private svc; + private svcVersion; + private text; + private lineMap; + private textVersion; + constructor(host: ServerHost, fileName: NormalizedPath); + getVersion(): string; + hasScriptVersionCache(): boolean; + useScriptVersionCache(newText?: string): void; + useText(newText?: string): void; + edit(start: number, end: number, newText: string): void; + reload(text: string): void; + reloadFromFile(tempFileName?: string): void; + getSnapshot(): IScriptSnapshot; + getLineInfo(line: number): ILineInfo; + lineToTextSpan(line: number): TextSpan; + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): ILineInfo; + private getFileText(tempFileName?); + private ensureNoScriptVersionCache(); + private switchToScriptVersionCache(newText?); + private getOrLoadText(); + private getLineMap(); + private setText(newText); + } class ScriptInfo { private readonly host; readonly fileName: NormalizedPath; readonly scriptKind: ScriptKind; - isOpen: boolean; hasMixedContent: boolean; readonly containingProjects: Project[]; private formatCodeSettings; readonly path: Path; private fileWatcher; - private svc; - constructor(host: ServerHost, fileName: NormalizedPath, content: string, scriptKind: ScriptKind, isOpen?: boolean, hasMixedContent?: boolean); + private textStorage; + private isOpen; + constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent?: boolean); + isScriptOpen(): boolean; + open(newText: string): void; + close(): void; + getSnapshot(): IScriptSnapshot; getFormatCodeSettings(): FormatCodeSettings; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; + registerFileUpdate(): void; setFormatOptions(formatSettings: FormatCodeSettings): void; setWatcher(watcher: FileWatcher): void; stopWatcher(): void; @@ -11004,7 +11068,6 @@ declare namespace ts.server { reload(script: string): void; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): void; - snap(): LineIndexSnapshot; getLineInfo(line: number): ILineInfo; editContent(start: number, end: number, newText: string): void; markContainingProjectsAsDirty(): void; @@ -11089,6 +11152,7 @@ declare namespace ts.server { getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; onProjectUpdateGraph(): void; emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; + clear(): void; } function createBuilder(project: Project): Builder; } @@ -11112,7 +11176,6 @@ declare namespace ts.server { get(path: Path): ReadonlyArray; set(path: Path, value: ReadonlyArray): void; } - function createNoSemanticFeaturesWrapper(realLanguageService: LanguageService): LanguageService; abstract class Project { private readonly projectName; readonly projectKind: ProjectKind; @@ -11127,9 +11190,9 @@ declare namespace ts.server { private cachedUnresolvedImportsPerFile; private lastCachedUnresolvedImportsList; private readonly languageService; - private readonly noSemanticFeaturesLanguageService; languageServiceEnabled: boolean; builder: Builder; + private updatedFileNames; private lastReportedFileNames; private lastReportedVersion; private projectStructureVersion; @@ -11168,6 +11231,7 @@ declare namespace ts.server { isRoot(info: ScriptInfo): boolean; addRoot(info: ScriptInfo): void; removeFile(info: ScriptInfo, detachFromProject?: boolean): void; + registerFileUpdate(fileName: string): void; markAsDirty(): void; private extractUnresolvedImportsFromSourceFile(file, result); updateGraph(): boolean; @@ -11267,9 +11331,10 @@ declare namespace ts.server { interface HostConfiguration { formatCodeOptions: FormatCodeSettings; hostInfo: string; + extraFileExtensions?: FileExtensionInfo[]; } interface OpenConfiguredProjectResult { - configFileName?: string; + configFileName?: NormalizedPath; configFileErrors?: Diagnostic[]; } class ProjectService { @@ -11353,7 +11418,8 @@ declare namespace ts.server { applyChangesInOpenFiles(openFiles: protocol.ExternalFile[], changedFiles: protocol.ChangedOpenFile[], closedFiles: string[]): void; private closeConfiguredProject(configFile); closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; - openExternalProject(proj: protocol.ExternalProject): void; + openExternalProjects(projects: protocol.ExternalProject[]): void; + openExternalProject(proj: protocol.ExternalProject, suppressRefreshOfInferredProjects?: boolean): void; } } declare namespace ts.server { diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 2a5358c51e6..d17a7d90330 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -137,7 +137,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.1.4"; + ts.version = "2.1.5"; })(ts || (ts = {})); (function (ts) { var createObject = Object.create; @@ -818,15 +818,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -1673,8 +1664,19 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -1685,11 +1687,11 @@ var ts; return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions) { + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -3207,6 +3209,7 @@ var ts; JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, @@ -5291,14 +5294,7 @@ var ts; } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -5538,9 +5534,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -5663,7 +5660,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -5767,7 +5764,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -5779,7 +5776,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; @@ -6897,6 +6894,7 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, writeLine: function () { return str_1 += " "; }, increaseIndent: ts.noop, @@ -7531,6 +7529,18 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 162) { + return node.elementType; + } + else if (node && node.kind === 157) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { @@ -8147,6 +8157,7 @@ var ts; cache = ts.concatenate(cache, node.jsDoc); } } + ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { if (!isParameter(param)) { return undefined; @@ -9502,39 +9513,6 @@ var ts; } return output; } - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - function stringifyFallback(value) { - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; function convertToBase64(input) { var result = ""; @@ -17784,7 +17762,7 @@ var ts; break; case 38: var asterisk = scanner.getTokenText(); - if (state === 1) { + if (state === 1 || state === 2) { state = 2; pushComment(asterisk); } @@ -17799,7 +17777,10 @@ var ts; break; case 5: var whitespace = scanner.getTokenText(); - if (state === 2 || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -17807,6 +17788,7 @@ var ts; case 1: break; default: + state = 2; pushComment(scanner.getTokenText()); break; } @@ -17896,7 +17878,7 @@ var ts; } function parseTagComments(indent) { var comments = []; - var state = 1; + var state = 0; var margin; function pushComment(text) { if (!margin) { @@ -22079,9 +22061,8 @@ var ts; } if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { - ts.Debug.assert(!!moduleNotFoundError); var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleName, resolvedModule.resolvedFileName); + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (compilerOptions.noImplicitAny && moduleNotFoundError) { error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); @@ -22310,6 +22291,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { return true; @@ -22323,26 +22314,28 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -23064,7 +23057,7 @@ var ts; } ts.Debug.assert(bindingElement.kind === 174); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 55); writeSpace(writer); } @@ -23679,16 +23672,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -23800,10 +23784,27 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216) { return getTypeOfInstantiatedSymbol(symbol); @@ -24574,8 +24575,8 @@ var ts; setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); var typeParameter = getTypeParameterFromMappedType(type); var constraintType = getConstraintTypeFromMappedType(type); - var homomorphicType = getHomomorphicTypeFromMappedType(type); var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getModifiersTypeFromMappedType(type); var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; @@ -24586,11 +24587,11 @@ var ts; var propType = instantiateType(templateType, templateMapper); if (t.flags & 32) { var propName = t.text; - var homomorphicProp = homomorphicType && getPropertyOfType(homomorphicType, propName); - var isOptional = templateOptional || !!(homomorphicProp && homomorphicProp.flags & 536870912); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); prop.type = propType; - prop.isReadonly = templateReadonly || homomorphicProp && isReadonlySymbol(homomorphicProp); + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); members[propName] = prop; } else if (t.flags & 2) { @@ -24613,9 +24614,20 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : unknownType); } - function getHomomorphicTypeFromMappedType(type) { - var constraint = getConstraintDeclaration(getTypeParameterFromMappedType(type)); - return constraint.kind === 168 ? instantiateType(getTypeFromTypeNode(constraint.type), type.mapper || identityMapper) : undefined; + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; } function getErasedTemplateTypeFromMappedType(type) { return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); @@ -24697,23 +24709,18 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } - function getApparentTypeOfIndexedAccess(type) { - return getIndexTypeOfType(getApparentType(type.objectType), 0) || type; - } function getApparentType(type) { - var t = type.flags & 16384 ? getApparentTypeOfTypeParameter(type) : - type.flags & 524288 ? getApparentTypeOfIndexedAccess(type) : - type; + var t = type.flags & 540672 ? getApparentTypeOfTypeVariable(type) : type; return t.flags & 262178 ? globalStringType : t.flags & 340 ? globalNumberType : t.flags & 136 ? globalBooleanType : @@ -25208,6 +25215,11 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143).parent); } @@ -25751,6 +25763,17 @@ var ts; var type = createType(524288); type.objectType = objectType; type.indexType = indexType; + if (type.objectType.flags & 229376) { + type.constraint = getIndexTypeOfType(type.objectType, 0); + } + else if (type.objectType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0); + } + } return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { @@ -25826,7 +25849,9 @@ var ts; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || isGenericMappedType(objectType)) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 178) || + isGenericMappedType(objectType)) { if (objectType.flags & 1) { return objectType; } @@ -26748,6 +26773,23 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } function isRelatedTo(source, target, reportErrors, headMessage) { var result; if (source.flags & 96 && source.flags & 1048576) { @@ -26770,7 +26812,7 @@ var ts; } return 0; } - if (target.flags & 196608) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } @@ -26801,7 +26843,7 @@ var ts; return result; } } - if (target.flags & 16384) { + else if (target.flags & 16384) { if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { var templateType = getTemplateTypeFromMappedType(source); @@ -26826,8 +26868,8 @@ var ts; return result; } } - if (target.type.flags & 16384) { - var constraint = getConstraintOfTypeParameter(target.type); + if (target.type.flags & 540672) { + var constraint = getConstraintOfTypeVariable(target.type); if (constraint) { if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { return result; @@ -26841,12 +26883,19 @@ var ts; return result; } } + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } if (source.flags & 16384) { if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } @@ -26863,6 +26912,14 @@ var ts; } } } + else if (source.flags & 524288) { + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } else { if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { @@ -29390,18 +29447,21 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { var container = ts.getThisContainer(node, true); var needToCaptureLexicalThis = false; if (container.kind === 150) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } if (container.kind === 185) { container = ts.getThisContainer(container, false); @@ -29515,6 +29575,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32) || isCallExpression) { nodeCheckFlag = 512; } @@ -29970,7 +30033,7 @@ var ts; return mapper && mapper.context; } function checkSpreadExpression(node, contextualMapper) { - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false); } function hasDefaultValue(node) { @@ -30185,8 +30248,10 @@ var ts; if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), true); } - spread.flags |= propagatedFlags; - spread.symbol = node.symbol; + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } return spread; } return createObjectLiteralType(); @@ -31469,12 +31534,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8) { @@ -32633,8 +32699,8 @@ var ts; } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); if (apparentType.flags & (2 | 4 | 8 | 16)) { return true; } @@ -33289,7 +33355,7 @@ var ts; checkSourceElement(node.type); var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - var keyType = constraintType.flags & 16384 ? getApparentTypeOfTypeParameter(constraintType) : constraintType; + var keyType = constraintType.flags & 540672 ? getApparentTypeOfTypeVariable(constraintType) : constraintType; checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { @@ -33578,7 +33644,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -33714,6 +33780,9 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; + } function checkDecorators(node) { if (!node.decorators) { return; @@ -33737,7 +33806,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -33746,11 +33815,13 @@ var ts; case 152: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markTypeNodeAsReferenced(node.type); break; case 147: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; case 144: markTypeNodeAsReferenced(node.type); break; @@ -33881,6 +33952,13 @@ var ts; } } } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } function errorUnusedLocal(node, name) { if (isIdentifierThatStartsWithUnderScore(node)) { var declaration = ts.getRootDeclaration(node.parent); @@ -33890,7 +33968,9 @@ var ts; return; } } - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -34809,7 +34889,7 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (languageVersion < 2) { + if (languageVersion < 2 && !ts.isInAmbientContext(node)) { checkExternalEmitHelpers(baseTypeNode.parent, 1); } var baseTypes = getBaseTypes(type); @@ -39466,10 +39546,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -39494,14 +39575,14 @@ var ts; } return { decorators: decorators }; } - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } function addClassElementDecorationStatements(statements, node, isStatic) { @@ -39526,7 +39607,7 @@ var ts; } function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -39549,7 +39630,7 @@ var ts; } function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -39577,35 +39658,35 @@ var ts; } return expressions; } - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(undefined, undefined, [], undefined, ts.createToken(35), serializeReturnTypeOfNode(node)))); @@ -39626,12 +39707,16 @@ var ts; return node.kind === 149; } function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 226 - || kind === 197 - || kind === 149 - || kind === 151 - || kind === 152; + switch (node.kind) { + case 226: + case 197: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149: + case 151: + case 152: + return true; + } + return false; } function serializeTypeOfNode(node) { switch (node.kind) { @@ -39649,18 +39734,7 @@ var ts; return ts.createVoidZero(); } } - function getRestParameterElementType(node) { - if (node && node.kind === 162) { - return node.elementType; - } - else if (node && node.kind === 157) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -39668,7 +39742,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -39676,7 +39750,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -39685,6 +39759,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } function serializeReturnTypeOfNode(node) { if (ts.isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); @@ -42582,12 +42665,17 @@ var ts; convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } + startLexicalEnvironment(); var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); var currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { + if (loopOutParameters.length || lexicalEnvironment) { var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1, statements_4); + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, undefined, true); } if (!ts.isBlock(loopBody)) { @@ -45456,11 +45544,11 @@ var ts; ], undefined, moduleBodyBlock); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); - var updated = ts.updateSourceFileNode(node, ts.createNodeArray([ + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) - ], node.statements)); + ], node.statements)), 1024); if (!(compilerOptions.outFile || compilerOptions.out)) { ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } @@ -46623,6 +46711,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -48232,7 +48321,7 @@ var ts; return; } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, @@ -48398,6 +48487,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -51926,7 +52018,9 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; @@ -52997,6 +53091,7 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -55010,13 +55105,14 @@ var ts; var symbols = completionData.symbols, location_3 = completionData.location; var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), kind: symbolKind, displayParts: displayParts, - documentation: documentation + documentation: documentation, + tags: tags }; } } @@ -55027,7 +55123,8 @@ var ts; kind: ts.ScriptElementKind.keyword, kindModifiers: ts.ScriptElementKindModifier.none, displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined + documentation: undefined, + tags: undefined }; } return undefined; @@ -57591,6 +57688,29 @@ var ts; return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getJsDocTagsFromDeclarations(declarations) { + var tags = []; + forEachUnique(declarations, function (declaration) { + var jsDocs = ts.getJSDocs(declaration); + if (!jsDocs) { + return; + } + for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { + var doc = jsDocs_1[_i]; + var tagsForDoc = doc.tags; + if (tagsForDoc) { + tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 279; }).map(function (jsDocTag) { + return { + name: jsDocTag.tagName.text, + text: jsDocTag.comment + }; + })); + } + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; function forEachUnique(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -57649,13 +57769,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 70 ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } var preamble = "/**" + newLine + indentationStr + " * "; @@ -59577,7 +59703,8 @@ var ts; suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: [ts.punctuationPart(25), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment() + documentation: candidateSignature.getDocumentationComment(), + tags: candidateSignature.getJsDocTags() }; }); var argumentIndex = argumentListInfo.argumentIndex; @@ -59714,6 +59841,7 @@ var ts; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; + var tags; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; @@ -59994,6 +60122,7 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); + tags = symbol.getJsDocTags(); if (documentation.length === 0 && symbol.flags & 4) { if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 261; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { @@ -60006,6 +60135,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(); + tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; } @@ -60013,7 +60143,7 @@ var ts; } } } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; function addNewLineIfDisplayPartsExist() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -60064,6 +60194,7 @@ var ts; displayParts.push(ts.punctuationPart(19)); } documentation = signature.getDocumentationComment(); + tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { @@ -62902,6 +63033,12 @@ var ts; } return this.documentationComment; }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; return SymbolObject; }()); var TokenObject = (function (_super) { @@ -62985,6 +63122,12 @@ var ts; } return this.documentationComment; }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; return SignatureObject; }()); var SourceFileObject = (function (_super) { @@ -63588,7 +63731,8 @@ var ts; kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined + documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } } @@ -63600,7 +63744,8 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation + documentation: displayPartsDocumentationsAndKind.documentation, + tags: displayPartsDocumentationsAndKind.tags }; } function getDefinitionAtPosition(fileName, position) { @@ -63886,7 +64031,7 @@ var ts; return false; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { @@ -64065,22 +64210,160 @@ var ts; (function (ts) { var server; (function (server) { + var TextStorage = (function () { + function TextStorage(host, fileName) { + this.host = host; + this.fileName = fileName; + this.svcVersion = 0; + this.textVersion = 0; + } + TextStorage.prototype.getVersion = function () { + return this.svc + ? "SVC-" + this.svcVersion + "-" + this.svc.getSnapshot().version + : "Text-" + this.textVersion; + }; + TextStorage.prototype.hasScriptVersionCache = function () { + return this.svc !== undefined; + }; + TextStorage.prototype.useScriptVersionCache = function (newText) { + this.switchToScriptVersionCache(newText); + }; + TextStorage.prototype.useText = function (newText) { + this.svc = undefined; + this.setText(newText); + }; + TextStorage.prototype.edit = function (start, end, newText) { + this.switchToScriptVersionCache().edit(start, end - start, newText); + }; + TextStorage.prototype.reload = function (text) { + if (this.svc) { + this.svc.reload(text); + } + else { + this.setText(text); + } + }; + TextStorage.prototype.reloadFromFile = function (tempFileName) { + if (this.svc || (tempFileName !== this.fileName)) { + this.reload(this.getFileText(tempFileName)); + } + else { + this.setText(undefined); + } + }; + TextStorage.prototype.getSnapshot = function () { + return this.svc + ? this.svc.getSnapshot() + : ts.ScriptSnapshot.fromString(this.getOrLoadText()); + }; + TextStorage.prototype.getLineInfo = function (line) { + return this.switchToScriptVersionCache().getSnapshot().index.lineNumberToInfo(line); + }; + TextStorage.prototype.lineToTextSpan = function (line) { + if (!this.svc) { + var lineMap = this.getLineMap(); + var start = lineMap[line]; + var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; + return ts.createTextSpanFromBounds(start, end); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + if (!this.svc) { + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1); + } + var index = this.svc.getSnapshot().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + TextStorage.prototype.positionToLineOffset = function (position) { + if (!this.svc) { + var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; + return { line: line + 1, offset: character + 1 }; + } + var index = this.svc.getSnapshot().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + TextStorage.prototype.getFileText = function (tempFileName) { + return this.host.readFile(tempFileName || this.fileName) || ""; + }; + TextStorage.prototype.ensureNoScriptVersionCache = function () { + ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); + }; + TextStorage.prototype.switchToScriptVersionCache = function (newText) { + if (!this.svc) { + this.svc = server.ScriptVersionCache.fromString(this.host, newText !== undefined ? newText : this.getOrLoadText()); + this.svcVersion++; + this.text = undefined; + } + return this.svc; + }; + TextStorage.prototype.getOrLoadText = function () { + this.ensureNoScriptVersionCache(); + if (this.text === undefined) { + this.setText(this.getFileText()); + } + return this.text; + }; + TextStorage.prototype.getLineMap = function () { + this.ensureNoScriptVersionCache(); + return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); + }; + TextStorage.prototype.setText = function (newText) { + this.ensureNoScriptVersionCache(); + if (newText === undefined || this.text !== newText) { + this.text = newText; + this.lineMap = undefined; + this.textVersion++; + } + }; + return TextStorage; + }()); + server.TextStorage = TextStorage; var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { - if (isOpen === void 0) { isOpen = false; } + function ScriptInfo(host, fileName, scriptKind, hasMixedContent) { if (hasMixedContent === void 0) { hasMixedContent = false; } this.host = host; this.fileName = fileName; this.scriptKind = scriptKind; - this.isOpen = isOpen; this.hasMixedContent = hasMixedContent; this.containingProjects = []; this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = server.ScriptVersionCache.fromString(host, content); + this.textStorage = new TextStorage(host, fileName); + if (hasMixedContent) { + this.textStorage.reload(""); + } this.scriptKind = scriptKind ? scriptKind : ts.getScriptKindFromFileName(fileName); } + ScriptInfo.prototype.isScriptOpen = function () { + return this.isOpen; + }; + ScriptInfo.prototype.open = function (newText) { + this.isOpen = true; + this.textStorage.useScriptVersionCache(newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.close = function () { + this.isOpen = false; + this.textStorage.useText(this.hasMixedContent ? "" : undefined); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.getSnapshot = function () { + return this.textStorage.getSnapshot(); + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatCodeSettings; }; @@ -64134,6 +64417,12 @@ var ts; } return this.containingProjects[0]; }; + ScriptInfo.prototype.registerFileUpdate = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.registerFileUpdate(this.path); + } + }; ScriptInfo.prototype.setFormatOptions = function (formatSettings) { if (formatSettings) { if (!this.formatCodeSettings) { @@ -64153,14 +64442,14 @@ var ts; } }; ScriptInfo.prototype.getLatestVersion = function () { - return this.svc.latestVersion().toString(); + return this.textStorage.getVersion(); }; ScriptInfo.prototype.reload = function (script) { - this.svc.reload(script); + this.textStorage.reload(script); this.markContainingProjectsAsDirty(); }; ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.snap(); + var snap = this.textStorage.getSnapshot(); this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; ScriptInfo.prototype.reloadFromFile = function (tempFileName) { @@ -64168,19 +64457,15 @@ var ts; this.reload(""); } else { - this.svc.reloadFromFile(tempFileName || this.fileName); + this.textStorage.reloadFromFile(tempFileName); this.markContainingProjectsAsDirty(); } }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); + return this.textStorage.getLineInfo(line); }; ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); + this.textStorage.edit(start, end, newText); this.markContainingProjectsAsDirty(); }; ScriptInfo.prototype.markContainingProjectsAsDirty = function () { @@ -64190,27 +64475,13 @@ var ts; } }; ScriptInfo.prototype.lineToTextSpan = function (line) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); + return this.textStorage.lineToTextSpan(line); }; ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { - var index = this.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); + return this.textStorage.lineOffsetToPosition(line, offset); }; ScriptInfo.prototype.positionToLineOffset = function (position) { - var index = this.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return this.textStorage.positionToLineOffset(position); }; return ScriptInfo; }()); @@ -64339,7 +64610,7 @@ var ts; LSHost.prototype.getScriptSnapshot = function (filename) { var scriptInfo = this.project.getScriptInfoLSHost(filename); if (scriptInfo) { - return scriptInfo.snap(); + return scriptInfo.getSnapshot(); } }; LSHost.prototype.getScriptFileNames = function () { @@ -64555,10 +64826,15 @@ var ts; function AbstractBuilder(project, ctor) { this.project = project; this.ctor = ctor; - this.fileInfos = ts.createFileMap(); } + AbstractBuilder.prototype.getFileInfos = function () { + return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createFileMap()); + }; + AbstractBuilder.prototype.clear = function () { + this.fileInfos_doNotAccessDirectly = undefined; + }; AbstractBuilder.prototype.getFileInfo = function (path) { - return this.fileInfos.get(path); + return this.getFileInfos().get(path); }; AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { var fileInfo = this.getFileInfo(path); @@ -64570,16 +64846,16 @@ var ts; return fileInfo; }; AbstractBuilder.prototype.getFileInfoPaths = function () { - return this.fileInfos.getKeys(); + return this.getFileInfos().getKeys(); }; AbstractBuilder.prototype.setFileInfo = function (path, info) { - this.fileInfos.set(path, info); + this.getFileInfos().set(path, info); }; AbstractBuilder.prototype.removeFileInfo = function (path) { - this.fileInfos.remove(path); + this.getFileInfos().remove(path); }; AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.fileInfos.forEachValue(function (_path, value) { return action(value); }); + this.getFileInfos().forEachValue(function (_path, value) { return action(value); }); }; AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { var fileInfo = this.getFileInfo(scriptInfo.path); @@ -64681,6 +64957,10 @@ var ts; _this.project = project; return _this; } + ModuleBuilder.prototype.clear = function () { + this.projectVersionForDependencyGraph = undefined; + _super.prototype.clear.call(this); + }; ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { var _this = this; if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { @@ -64877,107 +65157,6 @@ var ts; return UnresolvedImportsMap; }()); server.UnresolvedImportsMap = UnresolvedImportsMap; - var emptyResult = []; - var getEmptyResult = function () { return emptyResult; }; - var getUndefined = function () { return undefined; }; - var emptyEncodedSemanticClassifications = { spans: emptyResult, endOfLineState: 0 }; - function createNoSemanticFeaturesWrapper(realLanguageService) { - return { - cleanupSemanticCache: ts.noop, - getSyntacticDiagnostics: function (fileName) { - return fileName ? realLanguageService.getSyntacticDiagnostics(fileName) : emptyResult; - }, - getSemanticDiagnostics: getEmptyResult, - getCompilerOptionsDiagnostics: function () { - return realLanguageService.getCompilerOptionsDiagnostics(); - }, - getSyntacticClassifications: function (fileName, span) { - return realLanguageService.getSyntacticClassifications(fileName, span); - }, - getEncodedSyntacticClassifications: function (fileName, span) { - return realLanguageService.getEncodedSyntacticClassifications(fileName, span); - }, - getSemanticClassifications: getEmptyResult, - getEncodedSemanticClassifications: function () { - return emptyEncodedSemanticClassifications; - }, - getCompletionsAtPosition: getUndefined, - findReferences: getEmptyResult, - getCompletionEntryDetails: getUndefined, - getQuickInfoAtPosition: getUndefined, - findRenameLocations: getEmptyResult, - getNameOrDottedNameSpan: function (fileName, startPos, endPos) { - return realLanguageService.getNameOrDottedNameSpan(fileName, startPos, endPos); - }, - getBreakpointStatementAtPosition: function (fileName, position) { - return realLanguageService.getBreakpointStatementAtPosition(fileName, position); - }, - getBraceMatchingAtPosition: function (fileName, position) { - return realLanguageService.getBraceMatchingAtPosition(fileName, position); - }, - getSignatureHelpItems: getUndefined, - getDefinitionAtPosition: getEmptyResult, - getRenameInfo: function () { return ({ - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(ts.Diagnostics.Language_service_is_disabled), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }); }, - getTypeDefinitionAtPosition: getUndefined, - getReferencesAtPosition: getEmptyResult, - getDocumentHighlights: getEmptyResult, - getOccurrencesAtPosition: getEmptyResult, - getNavigateToItems: getEmptyResult, - getNavigationBarItems: function (fileName) { - return realLanguageService.getNavigationBarItems(fileName); - }, - getNavigationTree: function (fileName) { - return realLanguageService.getNavigationTree(fileName); - }, - getOutliningSpans: function (fileName) { - return realLanguageService.getOutliningSpans(fileName); - }, - getTodoComments: getEmptyResult, - getIndentationAtPosition: function (fileName, position, options) { - return realLanguageService.getIndentationAtPosition(fileName, position, options); - }, - getFormattingEditsForRange: function (fileName, start, end, options) { - return realLanguageService.getFormattingEditsForRange(fileName, start, end, options); - }, - getFormattingEditsForDocument: function (fileName, options) { - return realLanguageService.getFormattingEditsForDocument(fileName, options); - }, - getFormattingEditsAfterKeystroke: function (fileName, position, key, options) { - return realLanguageService.getFormattingEditsAfterKeystroke(fileName, position, key, options); - }, - getDocCommentTemplateAtPosition: function (fileName, position) { - return realLanguageService.getDocCommentTemplateAtPosition(fileName, position); - }, - isValidBraceCompletionAtPosition: function (fileName, position, openingBrace) { - return realLanguageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); - }, - getEmitOutput: getUndefined, - getProgram: function () { - return realLanguageService.getProgram(); - }, - getNonBoundSourceFile: function (fileName) { - return realLanguageService.getNonBoundSourceFile(fileName); - }, - dispose: function () { - return realLanguageService.dispose(); - }, - getCompletionEntrySymbol: getUndefined, - getImplementationAtPosition: getEmptyResult, - getSourceFile: function (fileName) { - return realLanguageService.getSourceFile(fileName); - }, - getCodeFixesAtPosition: getEmptyResult - }; - } - server.createNoSemanticFeaturesWrapper = createNoSemanticFeaturesWrapper; var Project = (function () { function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { this.projectName = projectName; @@ -65006,7 +65185,6 @@ var ts; this.lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); this.lsHost.setCompilationSettings(this.compilerOptions); this.languageService = ts.createLanguageService(this.lsHost, this.documentRegistry); - this.noSemanticFeaturesLanguageService = createNoSemanticFeaturesWrapper(this.languageService); if (!languageServiceEnabled) { this.disableLanguageService(); } @@ -65037,9 +65215,7 @@ var ts; if (ensureSynchronized) { this.updateGraph(); } - return this.languageServiceEnabled - ? this.languageService - : this.noSemanticFeaturesLanguageService; + return this.languageService; }; Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { if (!this.languageServiceEnabled) { @@ -65113,7 +65289,9 @@ var ts; if (this.rootFiles) { for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { var f = _a[_i]; - result.push(f.fileName); + if (this.languageServiceEnabled || f.isScriptOpen()) { + result.push(f.fileName); + } } if (this.typingFiles) { for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { @@ -65129,6 +65307,9 @@ var ts; }; Project.prototype.getScriptInfos = function () { var _this = this; + if (!this.languageServiceEnabled) { + return this.rootFiles; + } return ts.map(this.program.getSourceFiles(), function (sourceFile) { var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); if (!scriptInfo) { @@ -65187,7 +65368,7 @@ var ts; }; Project.prototype.containsFile = function (filename, requireOpen) { var info = this.projectService.getScriptInfoForNormalizedPath(filename); - if (info && (info.isOpen || !requireOpen)) { + if (info && (info.isScriptOpen() || !requireOpen)) { return this.containsScriptInfo(info); } }; @@ -65212,6 +65393,9 @@ var ts; } this.markAsDirty(); }; + Project.prototype.registerFileUpdate = function (fileName) { + (this.updatedFileNames || (this.updatedFileNames = ts.createMap()))[fileName] = fileName; + }; Project.prototype.markAsDirty = function () { this.projectStateVersion++; }; @@ -65244,9 +65428,6 @@ var ts; this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || server.emptyArray); }; Project.prototype.updateGraph = function () { - if (!this.languageServiceEnabled) { - return true; - } this.lsHost.startRecordingFilesWithChangedResolutions(); var hasChanges = this.updateGraphWorker(); var changedFiles = this.lsHost.finishRecordingFilesWithChangedResolutions() || server.emptyArray; @@ -65268,6 +65449,12 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } + if (this.languageServiceEnabled) { + this.builder.onProjectUpdateGraph(); + } + else { + this.builder.clear(); + } if (hasChanges) { this.projectStructureVersion++; } @@ -65300,7 +65487,6 @@ var ts; } } } - this.builder.onProjectUpdateGraph(); return hasChanges; }; Project.prototype.getScriptInfoLSHost = function (fileName) { @@ -65362,16 +65548,20 @@ var ts; projectName: this.getProjectName(), version: this.projectStructureVersion, isInferred: this.projectKind === ProjectKind.Inferred, - options: this.getCompilerOptions() + options: this.getCompilerOptions(), + languageServiceDisabled: !this.languageServiceEnabled }; + var updatedFileNames = this.updatedFileNames; + this.updatedFileNames = undefined; if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { - if (this.projectStructureVersion == this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) { return { info: info, projectErrors: this.projectErrors }; } var lastReportedFileNames = this.lastReportedFileNames; var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); var added = []; var removed = []; + var updated = ts.getOwnKeys(updatedFileNames); for (var id in currentFiles) { if (!ts.hasProperty(lastReportedFileNames, id)) { added.push(id); @@ -65384,7 +65574,7 @@ var ts; } this.lastReportedFileNames = currentFiles; this.lastReportedVersion = this.projectStructureVersion; - return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; + return { info: info, changes: { added: added, removed: removed, updated: updated }, projectErrors: this.projectErrors }; } else { var projectFileNames = this.getFileNames(); @@ -65710,7 +65900,10 @@ var ts; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (_) { return undefined; }, - hasMixedContent: function (_) { return false; } + hasMixedContent: function (fileName, extraFileExtensions) { + var mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, function (item) { return item.isMixedContent; }), function (item) { return item.extension; }); + return ts.forEach(mixedContentExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, @@ -65790,7 +65983,8 @@ var ts; this.typingsCache = new server.TypingsCache(this.typingsInstaller); this.hostConfiguration = { formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), - hostInfo: "Unknown host" + hostInfo: "Unknown host", + extraFileExtensions: [] }; this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); } @@ -65916,7 +66110,7 @@ var ts; this.handleDeletedFile(info); } else { - if (info && (!info.isOpen)) { + if (info && (!info.isScriptOpen())) { info.reloadFromFile(); this.updateProjectGraphs(info.containingProjects); } @@ -65925,7 +66119,7 @@ var ts; ProjectService.prototype.handleDeletedFile = function (info) { this.logger.info(info.fileName + " deleted"); info.stopWatcher(); - if (!info.isOpen) { + if (!info.isScriptOpen()) { this.filenameToScriptInfo.remove(info.path); this.lastDeletedFile = info; var containingProjects = info.containingProjects.slice(); @@ -65956,7 +66150,7 @@ var ts; }; ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { var _this = this; - if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) { return; } this.logger.info("Detected source file changes: " + fileName); @@ -66055,13 +66249,15 @@ var ts; } }; ProjectService.prototype.closeOpenFile = function (info) { - info.reloadFromFile(); + info.close(); server.removeItemFromSet(this.openFiles, info); - info.isOpen = false; var projectsToRemove; for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; if (p.projectKind === server.ProjectKind.Configured) { + if (info.hasMixedContent) { + info.registerFileUpdate(); + } if (p.deleteOpenRef() === 0) { (projectsToRemove || (projectsToRemove = [])).push(p); } @@ -66069,6 +66265,9 @@ var ts; else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { (projectsToRemove || (projectsToRemove = [])).push(p); } + if (!p.languageServiceEnabled) { + p.markAsDirty(); + } } if (projectsToRemove) { for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { @@ -66186,7 +66385,7 @@ var ts; config = sanitizedConfig; errors = diagnostics.length ? diagnostics : [result.error]; } - var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { errors = ts.concatenate(errors, parsedCommandLine.errors); } @@ -66265,7 +66464,7 @@ var ts; var f = files_4[_i]; var rootFilename = propertyReader.getFileName(f); var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); if (this.host.fileExists(rootFilename)) { var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); project.addRoot(info); @@ -66309,7 +66508,7 @@ var ts; rootFilesChanged = true; if (!scriptInfo) { var scriptKind = propertyReader.getScriptKind(f); - var hasMixedContent = propertyReader.hasMixedContent(f); + var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); } } @@ -66340,7 +66539,7 @@ var ts; if (toAdd) { for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { var f = toAdd_1[_d]; - if (f.isOpen && isRootFileInInferredProject(f)) { + if (f.isScriptOpen() && isRootFileInInferredProject(f)) { var inferredProject = f.containingProjects[0]; inferredProject.removeFile(f); if (!inferredProject.hasRoots()) { @@ -66379,9 +66578,7 @@ var ts; project.stopWatchingDirectory(); } else { - if (!project.languageServiceEnabled) { - project.enableLanguageService(); - } + project.enableLanguageService(); this.watchConfigDirectoryForProject(project, projectOptions); this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors); } @@ -66411,29 +66608,30 @@ var ts; var _this = this; var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); + if (openedByClient || this.host.fileExists(fileName)) { + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent); this.filenameToScriptInfo.set(info.path, info); - if (!info.isOpen && !hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + if (openedByClient) { + if (fileContent === undefined) { + fileContent = this.host.readFile(fileName) || ""; + } + } + else { + if (!hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } } } } if (info) { - if (fileContent !== undefined) { - info.reload(fileContent); + if (openedByClient && !info.isScriptOpen()) { + info.open(fileContent); + if (hasMixedContent) { + info.registerFileUpdate(); + } } - if (openedByClient) { - info.isOpen = true; + else if (fileContent !== undefined) { + info.reload(fileContent); } } return info; @@ -66461,6 +66659,10 @@ var ts; server.mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); this.logger.info("Format host information updated"); } + if (args.extraFileExtensions) { + this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; + this.logger.info("Host file extension mappings updated"); + } } }; ProjectService.prototype.closeLog = function () { @@ -66508,19 +66710,28 @@ var ts; return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { - var _a = this.findContainingExternalProject(fileName) - ? {} - : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; + var configFileName; + var configFileErrors; + var project = this.findContainingExternalProject(fileName); + if (!project) { + (_a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors); + if (configFileName) { + project = this.findConfiguredProjectByProjectName(configFileName); + } + } + if (project && !project.languageServiceEnabled) { + project.markAsDirty(); + } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); this.assignScriptInfoToInferredProjectIfNecessary(info, true); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; + var _a; }; ProjectService.prototype.closeClientFile = function (uncheckedFileName) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); if (info) { this.closeOpenFile(info); - info.isOpen = false; } this.printProjects(); }; @@ -66547,7 +66758,7 @@ var ts; for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { var file = openFiles_1[_i]; var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen()); var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); } @@ -66614,7 +66825,23 @@ var ts; } } }; - ProjectService.prototype.openExternalProject = function (proj) { + ProjectService.prototype.openExternalProjects = function (projects) { + var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; }); + for (var externalProjectName in this.externalProjectToConfiguredProjectMap) { + projectsToClose[externalProjectName] = true; + } + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var externalProject = projects_4[_i]; + this.openExternalProject(externalProject, true); + delete projectsToClose[externalProject.projectFileName]; + } + for (var externalProjectName in projectsToClose) { + this.closeExternalProject(externalProjectName, true); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.openExternalProject = function (proj, suppressRefreshOfInferredProjects) { + if (suppressRefreshOfInferredProjects === void 0) { suppressRefreshOfInferredProjects = false; } if (proj.typingOptions && !proj.typeAcquisition) { var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions); proj.typeAcquisition = typeAcquisition; @@ -66640,7 +66867,14 @@ var ts; var exisingConfigFiles; if (externalProject) { if (!tsConfigFiles) { - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typeAcquisition, proj.options.compileOnSave, undefined); + var compilerOptions = convertCompilerOptions(proj.options); + if (this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, proj.rootFiles, externalFilePropertyReader)) { + externalProject.disableLanguageService(); + } + else { + externalProject.enableLanguageService(); + } + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave, undefined); return; } this.closeExternalProject(proj.projectFileName, true); @@ -66692,7 +66926,9 @@ var ts; delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition); } - this.refreshInferredProjects(); + if (!suppressRefreshOfInferredProjects) { + this.refreshInferredProjects(); + } }; return ProjectService; }()); @@ -66854,14 +67090,11 @@ var ts; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, _a[CommandNames.OpenExternalProject] = function (request) { - _this.projectService.openExternalProject(request.arguments); + _this.projectService.openExternalProject(request.arguments, false); return _this.requiredResponse(true); }, _a[CommandNames.OpenExternalProjects] = function (request) { - for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { - var proj = _a[_i]; - _this.projectService.openExternalProject(proj); - } + _this.projectService.openExternalProjects(request.arguments.projects); return _this.requiredResponse(true); }, _a[CommandNames.CloseExternalProject] = function (request) { @@ -67258,8 +67491,8 @@ var ts; return; } this.logger.info("cleaning " + caption); - for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { - var p = projects_4[_i]; + for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) { + var p = projects_5[_i]; p.getLanguageService(false).cleanupSemanticCache(); } }; @@ -67555,7 +67788,7 @@ var ts; var displayString = ts.displayPartsToString(nameInfo.displayParts); var nameSpan = nameInfo.textSpan; var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; - var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); var refs = server.combineProjectOutput(projects, function (project) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { @@ -67565,7 +67798,7 @@ var ts; var refScriptInfo = project.getScriptInfo(ref.fileName); var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); - var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + var lineText = refScriptInfo.getSnapshot().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); return { file: ref.fileName, start: start, @@ -67676,6 +67909,7 @@ var ts; end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), displayString: displayString, documentation: docString, + tags: quickInfo.tags || [] }; } else { @@ -67815,6 +68049,9 @@ var ts; if (!project) { server.Errors.ThrowNoProject(); } + if (!project.languageServiceEnabled) { + return false; + } var scriptInfo = project.getScriptInfo(file); return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); }; @@ -68080,7 +68317,7 @@ var ts; highPriorityFiles.push(fileNameInProject); else { var info = this.projectService.getScriptInfo(fileNameInProject); - if (!info.isOpen) { + if (!info.isScriptOpen()) { if (fileNameInProject.indexOf(".d.ts") > 0) veryLowPriorityFiles.push(fileNameInProject); else @@ -68537,8 +68774,9 @@ var ts; } }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { - var oldSnap = oldSnapshot; - return this.getTextChangeRangeSinceVersion(oldSnap.version); + if (oldSnapshot instanceof LineIndexSnapshot) { + return this.getTextChangeRangeSinceVersion(oldSnapshot.version); + } }; return LineIndexSnapshot; }()); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 02a246f27be..c5c9ef37531 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1623,6 +1623,7 @@ declare namespace ts { writeSpace(text: string): void; writeStringLiteral(text: string): void; writeParameter(text: string): void; + writeProperty(text: string): void; writeSymbol(text: string, symbol: Symbol): void; writeLine(): void; increaseIndent(): void; @@ -1853,6 +1854,7 @@ declare namespace ts { interface IndexedAccessType extends TypeVariable { objectType: Type; indexType: Type; + constraint?: Type; } interface IndexType extends Type { type: TypeVariable | UnionOrIntersectionType; @@ -1875,6 +1877,11 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -2142,7 +2149,7 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version = "2.1.4"; + const version = "2.1.5"; } declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; @@ -2361,7 +2368,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; @@ -2394,6 +2401,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[]; getDocumentationComment(): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -2414,6 +2422,7 @@ declare namespace ts { getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; } interface SourceFile { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; @@ -2735,12 +2744,17 @@ declare namespace ts { text: string; kind: string; } + interface JSDocTagInfo { + name: string; + text?: string; + } interface QuickInfo { kind: string; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface RenameInfo { canRename: boolean; @@ -2771,6 +2785,7 @@ declare namespace ts { separatorDisplayParts: SymbolDisplayPart[]; parameters: SignatureHelpParameter[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } /** * Represents a set of signature help items, and the preferred item that should be selected. @@ -2809,6 +2824,7 @@ declare namespace ts { kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ diff --git a/lib/typescript.js b/lib/typescript.js index e76f7fa858c..bcbbaed99a5 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1187,7 +1187,7 @@ var ts; var ts; (function (ts) { /** The version of the TypeScript compiler release */ - ts.version = "2.1.4"; + ts.version = "2.1.5"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -2037,25 +2037,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - /** - * Reduce the properties defined on a map-like (but not from its prototype chain). - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * reduceProperties instead as it offers better performance. - * - * @param map The map-like to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. - */ - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; /** * Performs a shallow equality comparison of the contents of two map-likes. * @@ -2342,7 +2323,7 @@ var ts; return 1 /* GreaterThan */; if (ignoreCase) { if (ts.collator && String.prototype.localeCompare) { - // accent means a ≠ b, a ≠ á, a = A + // accent means a ? b, a ? a´, a = A var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; } @@ -3023,8 +3004,19 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3 /* TS */) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3035,11 +3027,11 @@ var ts; return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions) { + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -4657,6 +4649,7 @@ var ts; JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, @@ -6431,6 +6424,7 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. @@ -7154,6 +7148,24 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 162 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 157 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { @@ -7831,6 +7843,7 @@ var ts; cache = ts.concatenate(cache, node.jsDoc); } } + ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { if (!isParameter(param)) { return undefined; @@ -9355,47 +9368,6 @@ var ts; } return output; } - /** - * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph - * as the fallback implementation does not check for circular references by default. - */ - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - /** - * Serialize an object graph into a JSON string. - */ - function stringifyFallback(value) { - // JSON.stringify returns `undefined` here, instead of the string "undefined". - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -19462,7 +19434,7 @@ var ts; break; case 38 /* AsteriskToken */: var asterisk = scanner.getTokenText(); - if (state === 1 /* SawAsterisk */) { + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line state = 2 /* SavingComments */; pushComment(asterisk); @@ -19483,7 +19455,10 @@ var ts; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); - if (state === 2 /* SavingComments */ || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -19491,6 +19466,8 @@ var ts; case 1 /* EndOfFileToken */: break; default: + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } @@ -19581,7 +19558,7 @@ var ts; } function parseTagComments(indent) { var comments = []; - var state = 1 /* SawAsterisk */; + var state = 0 /* BeginningOfLine */; var margin; function pushComment(text) { if (!margin) { @@ -25415,9 +25392,8 @@ var ts; // May be an untyped module. If so, ignore resolutionDiagnostic. if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { - ts.Debug.assert(!!moduleNotFoundError); var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleName, resolvedModule.resolvedFileName); + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (compilerOptions.noImplicitAny && moduleNotFoundError) { error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); @@ -25672,6 +25648,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { @@ -25690,31 +25676,33 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 /* Alias */ - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 /* Alias */ + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) { + if (!useOnlyExternalAliasing || + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -26531,7 +26519,7 @@ var ts; } ts.Debug.assert(bindingElement.kind === 174 /* BindingElement */); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); } @@ -27259,18 +27247,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - // Variable has type annotation that circularly references the variable itself - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - // Variable has initializer that circularly references the variable itself - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -27390,10 +27367,29 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); @@ -28238,12 +28234,11 @@ var ts; // Resolve upfront such that recursive references see an empty object type. setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, - // and T as the template type. If K is of the form 'keyof S', the mapped type and S are - // homomorphic and we copy property modifiers from corresponding properties in S. + // and T as the template type. var typeParameter = getTypeParameterFromMappedType(type); var constraintType = getConstraintTypeFromMappedType(type); - var homomorphicType = getHomomorphicTypeFromMappedType(type); var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getModifiersTypeFromMappedType(type); var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; // First, if the constraint type is a type parameter, obtain the base constraint. Then, @@ -28262,11 +28257,11 @@ var ts; // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { var propName = t.text; - var homomorphicProp = homomorphicType && getPropertyOfType(homomorphicType, propName); - var isOptional = templateOptional || !!(homomorphicProp && homomorphicProp.flags & 536870912 /* Optional */); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912 /* Optional */); var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | (isOptional ? 536870912 /* Optional */ : 0), propName); prop.type = propType; - prop.isReadonly = templateReadonly || homomorphicProp && isReadonlySymbol(homomorphicProp); + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); members[propName] = prop; } else if (t.flags & 2 /* String */) { @@ -28289,9 +28284,26 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : unknownType); } - function getHomomorphicTypeFromMappedType(type) { - var constraint = getConstraintDeclaration(getTypeParameterFromMappedType(type)); - return constraint.kind === 168 /* TypeOperator */ ? instantiateType(getTypeFromTypeNode(constraint.type), type.mapper || identityMapper) : undefined; + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168 /* TypeOperator */) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; } function getErasedTemplateTypeFromMappedType(type) { return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); @@ -28383,31 +28395,23 @@ var ts; * The apparent type of a type parameter is the base constraint instantiated with the type parameter * as the type argument for the 'this' type. */ - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } - /** - * The apparent type of an indexed access T[K] is the type of T's string index signature, if any. - */ - function getApparentTypeOfIndexedAccess(type) { - return getIndexTypeOfType(getApparentType(type.objectType), 0 /* String */) || type; - } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 16384 /* TypeParameter */ ? getApparentTypeOfTypeParameter(type) : - type.flags & 524288 /* IndexedAccess */ ? getApparentTypeOfIndexedAccess(type) : - type; + var t = type.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(type) : type; return t.flags & 262178 /* StringLike */ ? globalStringType : t.flags & 340 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : @@ -28943,6 +28947,11 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 524288 /* IndexedAccess */ ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143 /* TypeParameter */).parent); } @@ -29552,6 +29561,24 @@ var ts; var type = createType(524288 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; + // We eagerly compute the constraint of the indexed access type such that circularity + // errors are immediately caught and reported. For example, class C { x: this["x"] } + // becomes an error only when the constraint is eagerly computed. + if (type.objectType.flags & 229376 /* StructuredType */) { + // The constraint of T[K], where T is an object, union, or intersection type, + // is the type of the string index signature of T, if any. + type.constraint = getIndexTypeOfType(type.objectType, 0 /* String */); + } + else if (type.objectType.flags & 540672 /* TypeVariable */) { + // The constraint of T[K], where T is a type variable, is A[K], where A is the + // apparent type of T. + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178 /* StringLike */) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0 /* String */); + } + } return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { @@ -29627,14 +29654,19 @@ var ts; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || isGenericMappedType(objectType)) { + // If the index type is generic, if the object type is generic and doesn't originate in an expression, + // or if the object type is a mapped type with a generic constraint, we are performing a higher-order + // index access where we cannot meaningfully access the properties of the object type. Note that for a + // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to + // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved + // eagerly using the constraint type of 'this' at the given location. + if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || + maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 178 /* ElementAccessExpression */) || + isGenericMappedType(objectType)) { if (objectType.flags & 1 /* Any */) { return objectType; } - // If the index type is generic or if the object type is a mapped type with a generic constraint, - // we are performing a higher-order index access where we cannot meaningfully access the properties - // of the object type. In those cases, we first check that the index type is assignable to 'keyof T' - // for the object type. + // We first check that the index type is assignable to 'keyof T' for the object type. if (accessNode) { if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -29651,6 +29683,7 @@ var ts; var id = objectType.id + "," + indexType.id; return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); } + // In the following we resolve T[K] to the type of the property in T selected by K. var apparentObjectType = getApparentType(objectType); if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { var propTypes = []; @@ -30651,6 +30684,25 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or @@ -30682,7 +30734,7 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 196608 /* UnionOrIntersection */) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } @@ -30729,7 +30781,7 @@ var ts; return result; } } - if (target.flags & 16384 /* TypeParameter */) { + else if (target.flags & 16384 /* TypeParameter */) { // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { @@ -30758,10 +30810,10 @@ var ts; return result; } } - // Given a type parameter T with a constraint C, a type S is assignable to + // Given a type variable T with a constraint C, a type S is assignable to // keyof T if S is assignable to keyof C. - if (target.type.flags & 16384 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(target.type); + if (target.type.flags & 540672 /* TypeVariable */) { + var constraint = getConstraintOfTypeVariable(target.type); if (constraint) { if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { return result; @@ -30777,6 +30829,14 @@ var ts; return result; } } + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } if (source.flags & 16384 /* TypeParameter */) { // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. @@ -30784,6 +30844,7 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } @@ -30802,6 +30863,16 @@ var ts; } } } + else if (source.flags & 524288 /* IndexedAccess */) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } else { if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments @@ -33680,30 +33751,33 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; if (container.kind === 150 /* Constructor */) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - // If a containing class does not have extends clause or the class extends null - // skip checking whether super statement is called before "this" accessing. - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - // We should give an error in the following cases: - // - No super-call - // - "this" is accessing before super-call. - // i.e super(this) - // this.x; super(); - // We want to make sure that super-call is done before accessing "this" so that - // "this" is not accessed as a parameter of the super-call. - if (!superCall || superCall.end > node.pos) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === 185 /* ArrowFunction */) { @@ -33832,6 +33906,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } @@ -34440,13 +34517,7 @@ var ts; return mapper && mapper.context; } function checkSpreadExpression(node, contextualMapper) { - // It is usually not safe to call checkExpressionCached if we can be contextually typing. - // You can tell that we are contextually typing because of the contextualMapper parameter. - // While it is true that a spread element can have a contextual type, it does not do anything - // with this type. It is neither affected by it, nor does it propagate it to its operand. - // So the fact that contextualMapper is passed is not important, because the operand of a spread - // element is not contextually typed. - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { @@ -34714,8 +34785,11 @@ var ts; if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); } - spread.flags |= propagatedFlags; - spread.symbol = node.symbol; + if (spread.flags & 32768 /* Object */) { + // only set the symbol and flags if this is a (fresh) object type + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } return spread; } return createObjectLiteralType(); @@ -36431,12 +36505,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 /* Protected */ && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8 /* Private */) { @@ -37807,8 +37882,8 @@ var ts; } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384 /* TypeParameter */) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672 /* TypeVariable */) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); // If the type parameter is constrained to the base primitive type we're checking for, // consider this a literal context. For example, given a type parameter 'T extends string', // this causes us to infer string literal types for T. @@ -38549,7 +38624,7 @@ var ts; checkSourceElement(node.type); var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - var keyType = constraintType.flags & 16384 /* TypeParameter */ ? getApparentTypeOfTypeParameter(constraintType) : constraintType; + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(constraintType) : constraintType; checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { @@ -38889,7 +38964,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -39131,6 +39206,9 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; + } /** Check the decorators of a node */ function checkDecorators(node) { if (!node.decorators) { @@ -39158,7 +39236,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -39167,11 +39245,13 @@ var ts; case 152 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markTypeNodeAsReferenced(node.type); break; case 147 /* PropertyDeclaration */: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; case 144 /* Parameter */: markTypeNodeAsReferenced(node.type); break; @@ -39323,6 +39403,13 @@ var ts; } } } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } function errorUnusedLocal(node, name) { if (isIdentifierThatStartsWithUnderScore(node)) { var declaration = ts.getRootDeclaration(node.parent); @@ -39332,7 +39419,9 @@ var ts; return; } } - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 /* Identifier */ ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -40472,7 +40561,7 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (languageVersion < 2 /* ES2015 */) { + if (languageVersion < 2 /* ES2015 */ && !ts.isInAmbientContext(node)) { checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); } var baseTypes = getBaseTypes(type); @@ -46247,10 +46336,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -46291,14 +46381,14 @@ var ts; * @param node The declaration node. * @param allDecorators An object containing all of the decorators for the declaration. */ - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } /** @@ -46345,7 +46435,7 @@ var ts; */ function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -46408,7 +46498,7 @@ var ts; */ function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -46454,35 +46544,35 @@ var ts; * @param node The declaration node. * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); @@ -46524,12 +46614,16 @@ var ts; * @param node The node to test. */ function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 226 /* ClassDeclaration */ - || kind === 197 /* ClassExpression */ - || kind === 149 /* MethodDeclaration */ - || kind === 151 /* GetAccessor */ - || kind === 152 /* SetAccessor */; + switch (node.kind) { + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return true; + } + return false; } /** * Serializes the type of a node for use with decorator type metadata. @@ -46552,29 +46646,12 @@ var ts; return ts.createVoidZero(); } } - /** - * Gets the most likely element type for a TypeNode. This is not an exhaustive test - * as it assumes a rest argument can only be an array type (either T[], or Array). - * - * @param node The type node. - */ - function getRestParameterElementType(node) { - if (node && node.kind === 162 /* ArrayType */) { - return node.elementType; - } - else if (node && node.kind === 157 /* TypeReference */) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } /** * Serializes the types of the parameters of a node for use with decorator type metadata. * * @param node The node that should have its parameter types serialized. */ - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -46582,7 +46659,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -46590,7 +46667,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -46599,6 +46676,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } /** * Serializes the return type of a node for use with decorator type metadata. * @@ -50842,12 +50928,17 @@ var ts; convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } + startLexicalEnvironment(); var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); var currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { + if (loopOutParameters.length || lexicalEnvironment) { var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*location*/ undefined, /*multiline*/ true); } if (!ts.isBlock(loopBody)) { @@ -54556,12 +54647,12 @@ var ts; // So the helper will be emit at the correct position instead of at the top of the source-file var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); - var updated = ts.updateSourceFileNode(node, ts.createNodeArray([ + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) - ], node.statements)); + ], node.statements)), 1024 /* NoTrailingComments */); if (!(compilerOptions.outFile || compilerOptions.out)) { ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } @@ -57503,7 +57594,7 @@ var ts; return; } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, @@ -57691,6 +57782,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -58000,6 +58094,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -63968,14 +64063,7 @@ var ts; ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; /* @internal */ function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ @@ -64259,9 +64347,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -64389,7 +64478,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -64566,7 +64655,7 @@ var ts; * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the @@ -64593,7 +64682,7 @@ var ts; var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (fileNames) { @@ -64790,7 +64879,9 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; @@ -66063,6 +66154,7 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -67861,13 +67953,14 @@ var ts; // completion entry. var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), kind: symbolKind, displayParts: displayParts, - documentation: documentation + documentation: documentation, + tags: tags }; } } @@ -67879,7 +67972,8 @@ var ts; kind: ts.ScriptElementKind.keyword, kindModifiers: ts.ScriptElementKindModifier.none, displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined + documentation: undefined, + tags: undefined }; } return undefined; @@ -70939,6 +71033,30 @@ var ts; return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getJsDocTagsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once. + var tags = []; + forEachUnique(declarations, function (declaration) { + var jsDocs = ts.getJSDocs(declaration); + if (!jsDocs) { + return; + } + for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { + var doc = jsDocs_1[_i]; + var tagsForDoc = doc.tags; + if (tagsForDoc) { + tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 279 /* JSDocTag */; }).map(function (jsDocTag) { + return { + name: jsDocTag.tagName.text, + text: jsDocTag.comment + }; + })); + } + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; /** * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. @@ -71031,13 +71149,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 70 /* Identifier */ ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } // A doc comment consists of the following // * The opening comment line @@ -73713,7 +73837,8 @@ var ts; suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: [ts.punctuationPart(25 /* CommaToken */), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment() + documentation: candidateSignature.getDocumentationComment(), + tags: candidateSignature.getJsDocTags() }; }); var argumentIndex = argumentListInfo.argumentIndex; @@ -73857,6 +73982,7 @@ var ts; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; + var tags; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; @@ -74161,6 +74287,7 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); + tags = symbol.getJsDocTags(); if (documentation.length === 0 && symbol.flags & 4 /* Property */) { // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. @@ -74176,6 +74303,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(); + tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; } @@ -74183,7 +74311,7 @@ var ts; } } } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; function addNewLineIfDisplayPartsExist() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -74234,6 +74362,7 @@ var ts; displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } documentation = signature.getDocumentationComment(); + tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { @@ -78257,6 +78386,12 @@ var ts; } return this.documentationComment; }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; return SymbolObject; }()); var TokenObject = (function (_super) { @@ -78340,6 +78475,12 @@ var ts; } return this.documentationComment; }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; return SignatureObject; }()); var SourceFileObject = (function (_super) { @@ -79044,7 +79185,8 @@ var ts; kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined + documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } } @@ -79056,7 +79198,8 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation + documentation: displayPartsDocumentationsAndKind.documentation, + tags: displayPartsDocumentationsAndKind.tags }; } /// Goto definition @@ -79378,7 +79521,7 @@ var ts; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index dd493cd5bd1..ae393065ff3 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1623,6 +1623,7 @@ declare namespace ts { writeSpace(text: string): void; writeStringLiteral(text: string): void; writeParameter(text: string): void; + writeProperty(text: string): void; writeSymbol(text: string, symbol: Symbol): void; writeLine(): void; increaseIndent(): void; @@ -1853,6 +1854,7 @@ declare namespace ts { interface IndexedAccessType extends TypeVariable { objectType: Type; indexType: Type; + constraint?: Type; } interface IndexType extends Type { type: TypeVariable | UnionOrIntersectionType; @@ -1875,6 +1877,11 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } + interface FileExtensionInfo { + extension: string; + scriptKind: ScriptKind; + isMixedContent: boolean; + } interface DiagnosticMessage { key: string; category: DiagnosticCategory; @@ -2142,7 +2149,7 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version = "2.1.4"; + const version = "2.1.5"; } declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; @@ -2361,7 +2368,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; @@ -2394,6 +2401,7 @@ declare namespace ts { getName(): string; getDeclarations(): Declaration[]; getDocumentationComment(): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; } interface Type { getFlags(): TypeFlags; @@ -2414,6 +2422,7 @@ declare namespace ts { getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; } interface SourceFile { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; @@ -2735,12 +2744,17 @@ declare namespace ts { text: string; kind: string; } + interface JSDocTagInfo { + name: string; + text?: string; + } interface QuickInfo { kind: string; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface RenameInfo { canRename: boolean; @@ -2771,6 +2785,7 @@ declare namespace ts { separatorDisplayParts: SymbolDisplayPart[]; parameters: SignatureHelpParameter[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } /** * Represents a set of signature help items, and the preferred item that should be selected. @@ -2809,6 +2824,7 @@ declare namespace ts { kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; + tags: JSDocTagInfo[]; } interface OutliningSpan { /** The span of the document to actually collapse. */ diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index e76f7fa858c..bcbbaed99a5 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1187,7 +1187,7 @@ var ts; var ts; (function (ts) { /** The version of the TypeScript compiler release */ - ts.version = "2.1.4"; + ts.version = "2.1.5"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -2037,25 +2037,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - /** - * Reduce the properties defined on a map-like (but not from its prototype chain). - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * reduceProperties instead as it offers better performance. - * - * @param map The map-like to reduce - * @param callback An aggregation function that is called for each entry in the map - * @param initial The initial value for the reduction. - */ - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; /** * Performs a shallow equality comparison of the contents of two map-likes. * @@ -2342,7 +2323,7 @@ var ts; return 1 /* GreaterThan */; if (ignoreCase) { if (ts.collator && String.prototype.localeCompare) { - // accent means a ≠ b, a ≠ á, a = A + // accent means a ? b, a ? a´, a = A var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; } @@ -3023,8 +3004,19 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3 /* TS */) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -3035,11 +3027,11 @@ var ts; return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions) { + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -4657,6 +4649,7 @@ var ts; JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, @@ -6431,6 +6424,7 @@ var ts; writeSpace: writeText, writeStringLiteral: writeText, writeParameter: writeText, + writeProperty: writeText, writeSymbol: writeText, // Completely ignore indentation for string writers. And map newlines to // a single space. @@ -7154,6 +7148,24 @@ var ts; } } ts.forEachYieldExpression = forEachYieldExpression; + /** + * Gets the most likely element type for a TypeNode. This is not an exhaustive test + * as it assumes a rest argument can only be an array type (either T[], or Array). + * + * @param node The type node. + */ + function getRestParameterElementType(node) { + if (node && node.kind === 162 /* ArrayType */) { + return node.elementType; + } + else if (node && node.kind === 157 /* TypeReference */) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; function isVariableLike(node) { if (node) { switch (node.kind) { @@ -7831,6 +7843,7 @@ var ts; cache = ts.concatenate(cache, node.jsDoc); } } + ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { if (!isParameter(param)) { return undefined; @@ -9355,47 +9368,6 @@ var ts; } return output; } - /** - * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph - * as the fallback implementation does not check for circular references by default. - */ - ts.stringify = typeof JSON !== "undefined" && JSON.stringify - ? JSON.stringify - : stringifyFallback; - /** - * Serialize an object graph into a JSON string. - */ - function stringifyFallback(value) { - // JSON.stringify returns `undefined` here, instead of the string "undefined". - return value === undefined ? undefined : stringifyValue(value); - } - function stringifyValue(value) { - return typeof value === "string" ? "\"" + escapeString(value) + "\"" - : typeof value === "number" ? isFinite(value) ? String(value) : "null" - : typeof value === "boolean" ? value ? "true" : "false" - : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) - : "null"; - } - function cycleCheck(cb, value) { - ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); - value.__cycle = true; - var result = cb(value); - delete value.__cycle; - return result; - } - function stringifyArray(value) { - return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; - } - function stringifyElement(memo, value) { - return (memo ? memo + "," : memo) + stringifyValue(value); - } - function stringifyObject(value) { - return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}"; - } - function stringifyProperty(memo, value, key) { - return value === undefined || typeof value === "function" || key === "__cycle" ? memo - : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); - } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** * Converts a string to a base-64 encoded ASCII string. @@ -19462,7 +19434,7 @@ var ts; break; case 38 /* AsteriskToken */: var asterisk = scanner.getTokenText(); - if (state === 1 /* SawAsterisk */) { + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { // If we've already seen an asterisk, then we can no longer parse a tag on this line state = 2 /* SavingComments */; pushComment(asterisk); @@ -19483,7 +19455,10 @@ var ts; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); - if (state === 2 /* SavingComments */ || margin !== undefined && indent + whitespace.length > margin) { + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { comments.push(whitespace.slice(margin - indent - 1)); } indent += whitespace.length; @@ -19491,6 +19466,8 @@ var ts; case 1 /* EndOfFileToken */: break; default: + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; } @@ -19581,7 +19558,7 @@ var ts; } function parseTagComments(indent) { var comments = []; - var state = 1 /* SawAsterisk */; + var state = 0 /* BeginningOfLine */; var margin; function pushComment(text) { if (!margin) { @@ -25415,9 +25392,8 @@ var ts; // May be an untyped module. If so, ignore resolutionDiagnostic. if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { if (isForAugmentation) { - ts.Debug.assert(!!moduleNotFoundError); var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleName, resolvedModule.resolvedFileName); + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (compilerOptions.noImplicitAny && moduleNotFoundError) { error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); @@ -25672,6 +25648,16 @@ var ts; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; function canQualifySymbol(symbolFromSymbolTable, meaning) { // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { @@ -25690,31 +25676,33 @@ var ts; canQualifySymbol(symbolFromSymbolTable, meaning); } } - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols[symbol.name])) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 /* Alias */ - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols[symbol.name])) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachProperty(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 /* Alias */ + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) { + if (!useOnlyExternalAliasing || + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } } } - } - }); + }); + } } if (symbol) { if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { @@ -26531,7 +26519,7 @@ var ts; } ts.Debug.assert(bindingElement.kind === 174 /* BindingElement */); if (bindingElement.propertyName) { - writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol); + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); } @@ -27259,18 +27247,7 @@ var ts; type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); } if (!popTypeResolution()) { - if (symbol.valueDeclaration.type) { - // Variable has type annotation that circularly references the variable itself - type = unknownType; - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - } - else { - // Variable has initializer that circularly references the variable itself - type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - } + type = reportCircularityError(symbol); } links.type = type; } @@ -27390,10 +27367,29 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; } return links.type; } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (symbol.valueDeclaration.type) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } function getTypeOfSymbol(symbol) { if (symbol.flags & 16777216 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); @@ -28238,12 +28234,11 @@ var ts; // Resolve upfront such that recursive references see an empty object type. setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, - // and T as the template type. If K is of the form 'keyof S', the mapped type and S are - // homomorphic and we copy property modifiers from corresponding properties in S. + // and T as the template type. var typeParameter = getTypeParameterFromMappedType(type); var constraintType = getConstraintTypeFromMappedType(type); - var homomorphicType = getHomomorphicTypeFromMappedType(type); var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getModifiersTypeFromMappedType(type); var templateReadonly = !!type.declaration.readonlyToken; var templateOptional = !!type.declaration.questionToken; // First, if the constraint type is a type parameter, obtain the base constraint. Then, @@ -28262,11 +28257,11 @@ var ts; // Otherwise, for type string create a string index signature. if (t.flags & 32 /* StringLiteral */) { var propName = t.text; - var homomorphicProp = homomorphicType && getPropertyOfType(homomorphicType, propName); - var isOptional = templateOptional || !!(homomorphicProp && homomorphicProp.flags & 536870912 /* Optional */); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912 /* Optional */); var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | (isOptional ? 536870912 /* Optional */ : 0), propName); prop.type = propType; - prop.isReadonly = templateReadonly || homomorphicProp && isReadonlySymbol(homomorphicProp); + prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); members[propName] = prop; } else if (t.flags & 2 /* String */) { @@ -28289,9 +28284,26 @@ var ts; instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : unknownType); } - function getHomomorphicTypeFromMappedType(type) { - var constraint = getConstraintDeclaration(getTypeParameterFromMappedType(type)); - return constraint.kind === 168 /* TypeOperator */ ? instantiateType(getTypeFromTypeNode(constraint.type), type.mapper || identityMapper) : undefined; + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 168 /* TypeOperator */) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; } function getErasedTemplateTypeFromMappedType(type) { return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType)); @@ -28383,31 +28395,23 @@ var ts; * The apparent type of a type parameter is the base constraint instantiated with the type parameter * as the type argument for the 'this' type. */ - function getApparentTypeOfTypeParameter(type) { + function getApparentTypeOfTypeVariable(type) { if (!type.resolvedApparentType) { - var constraintType = getConstraintOfTypeParameter(type); + var constraintType = getConstraintOfTypeVariable(type); while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { - constraintType = getConstraintOfTypeParameter(constraintType); + constraintType = getConstraintOfTypeVariable(constraintType); } type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); } return type.resolvedApparentType; } - /** - * The apparent type of an indexed access T[K] is the type of T's string index signature, if any. - */ - function getApparentTypeOfIndexedAccess(type) { - return getIndexTypeOfType(getApparentType(type.objectType), 0 /* String */) || type; - } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 16384 /* TypeParameter */ ? getApparentTypeOfTypeParameter(type) : - type.flags & 524288 /* IndexedAccess */ ? getApparentTypeOfIndexedAccess(type) : - type; + var t = type.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(type) : type; return t.flags & 262178 /* StringLike */ ? globalStringType : t.flags & 340 /* NumberLike */ ? globalNumberType : t.flags & 136 /* BooleanLike */ ? globalBooleanType : @@ -28943,6 +28947,11 @@ var ts; } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } + function getConstraintOfTypeVariable(type) { + return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 524288 /* IndexedAccess */ ? type.constraint : + undefined; + } function getParentSymbolOfTypeParameter(typeParameter) { return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143 /* TypeParameter */).parent); } @@ -29552,6 +29561,24 @@ var ts; var type = createType(524288 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; + // We eagerly compute the constraint of the indexed access type such that circularity + // errors are immediately caught and reported. For example, class C { x: this["x"] } + // becomes an error only when the constraint is eagerly computed. + if (type.objectType.flags & 229376 /* StructuredType */) { + // The constraint of T[K], where T is an object, union, or intersection type, + // is the type of the string index signature of T, if any. + type.constraint = getIndexTypeOfType(type.objectType, 0 /* String */); + } + else if (type.objectType.flags & 540672 /* TypeVariable */) { + // The constraint of T[K], where T is a type variable, is A[K], where A is the + // apparent type of T. + var apparentType = getApparentTypeOfTypeVariable(type.objectType); + if (apparentType !== emptyObjectType) { + type.constraint = isTypeOfKind(type.indexType, 262178 /* StringLike */) ? + getIndexedAccessType(apparentType, type.indexType) : + getIndexTypeOfType(apparentType, 0 /* String */); + } + } return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { @@ -29627,14 +29654,19 @@ var ts; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || isGenericMappedType(objectType)) { + // If the index type is generic, if the object type is generic and doesn't originate in an expression, + // or if the object type is a mapped type with a generic constraint, we are performing a higher-order + // index access where we cannot meaningfully access the properties of the object type. Note that for a + // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to + // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved + // eagerly using the constraint type of 'this' at the given location. + if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || + maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 178 /* ElementAccessExpression */) || + isGenericMappedType(objectType)) { if (objectType.flags & 1 /* Any */) { return objectType; } - // If the index type is generic or if the object type is a mapped type with a generic constraint, - // we are performing a higher-order index access where we cannot meaningfully access the properties - // of the object type. In those cases, we first check that the index type is assignable to 'keyof T' - // for the object type. + // We first check that the index type is assignable to 'keyof T' for the object type. if (accessNode) { if (!isTypeAssignableTo(indexType, getIndexType(objectType))) { error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -29651,6 +29683,7 @@ var ts; var id = objectType.id + "," + indexType.id; return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType)); } + // In the following we resolve T[K] to the type of the property in T selected by K. var apparentObjectType = getApparentType(objectType); if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { var propTypes = []; @@ -30651,6 +30684,25 @@ var ts; reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); } } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or @@ -30682,7 +30734,7 @@ var ts; // and intersection types are further deconstructed on the target side, we don't want to // make the check again (as it might fail for a partial target type). Therefore we obtain // the regular source type and proceed with that. - if (target.flags & 196608 /* UnionOrIntersection */) { + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { source = getRegularTypeOfObjectLiteral(source); } } @@ -30729,7 +30781,7 @@ var ts; return result; } } - if (target.flags & 16384 /* TypeParameter */) { + else if (target.flags & 16384 /* TypeParameter */) { // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!source.declaration.questionToken) { @@ -30758,10 +30810,10 @@ var ts; return result; } } - // Given a type parameter T with a constraint C, a type S is assignable to + // Given a type variable T with a constraint C, a type S is assignable to // keyof T if S is assignable to keyof C. - if (target.type.flags & 16384 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(target.type); + if (target.type.flags & 540672 /* TypeVariable */) { + var constraint = getConstraintOfTypeVariable(target.type); if (constraint) { if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { return result; @@ -30777,6 +30829,14 @@ var ts; return result; } } + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. + if (target.constraint) { + if (result = isRelatedTo(source, target.constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } if (source.flags & 16384 /* TypeParameter */) { // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. @@ -30784,6 +30844,7 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; return result; } } @@ -30802,6 +30863,16 @@ var ts; } } } + else if (source.flags & 524288 /* IndexedAccess */) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. + if (source.constraint) { + if (result = isRelatedTo(source.constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } else { if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // We have type references to same target type, see if relationship holds for all type arguments @@ -33680,30 +33751,33 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); return baseConstructorType === nullWideningType; } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } function checkThisExpression(node) { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; if (container.kind === 150 /* Constructor */) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - // If a containing class does not have extends clause or the class extends null - // skip checking whether super statement is called before "this" accessing. - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - // We should give an error in the following cases: - // - No super-call - // - "this" is accessing before super-call. - // i.e super(this) - // this.x; super(); - // We want to make sure that super-call is done before accessing "this" so that - // "this" is not accessed as a parameter of the super-call. - if (!superCall || superCall.end > node.pos) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - } + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === 185 /* ArrowFunction */) { @@ -33832,6 +33906,9 @@ var ts; } return unknownType; } + if (!isCallExpression && container.kind === 150 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } @@ -34440,13 +34517,7 @@ var ts; return mapper && mapper.context; } function checkSpreadExpression(node, contextualMapper) { - // It is usually not safe to call checkExpressionCached if we can be contextually typing. - // You can tell that we are contextually typing because of the contextualMapper parameter. - // While it is true that a spread element can have a contextual type, it does not do anything - // with this type. It is neither affected by it, nor does it propagate it to its operand. - // So the fact that contextualMapper is passed is not important, because the operand of a spread - // element is not contextually typed. - var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + var arrayOrIterableType = checkExpression(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } function hasDefaultValue(node) { @@ -34714,8 +34785,11 @@ var ts; if (propertiesArray.length > 0) { spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true); } - spread.flags |= propagatedFlags; - spread.symbol = node.symbol; + if (spread.flags & 32768 /* Object */) { + // only set the symbol and flags if this is a (fresh) object type + spread.flags |= propagatedFlags; + spread.symbol = node.symbol; + } return spread; } return createObjectLiteralType(); @@ -36431,12 +36505,13 @@ var ts; if (containingClass) { var containingType = getTypeOfNode(containingClass); var baseTypes = getBaseTypes(containingType); - if (baseTypes.length) { + while (baseTypes.length) { var baseType = baseTypes[0]; if (modifiers & 16 /* Protected */ && baseType.symbol === declaration.parent.symbol) { return true; } + baseTypes = getBaseTypes(baseType); } } if (modifiers & 8 /* Private */) { @@ -37807,8 +37882,8 @@ var ts; } function isLiteralContextualType(contextualType) { if (contextualType) { - if (contextualType.flags & 16384 /* TypeParameter */) { - var apparentType = getApparentTypeOfTypeParameter(contextualType); + if (contextualType.flags & 540672 /* TypeVariable */) { + var apparentType = getApparentTypeOfTypeVariable(contextualType); // If the type parameter is constrained to the base primitive type we're checking for, // consider this a literal context. For example, given a type parameter 'T extends string', // this causes us to infer string literal types for T. @@ -38549,7 +38624,7 @@ var ts; checkSourceElement(node.type); var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - var keyType = constraintType.flags & 16384 /* TypeParameter */ ? getApparentTypeOfTypeParameter(constraintType) : constraintType; + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentTypeOfTypeVariable(constraintType) : constraintType; checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint); } function isPrivateWithinAmbient(node) { @@ -38889,7 +38964,7 @@ var ts; if (thenSignatures.length === 0) { return undefined; } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -39131,6 +39206,9 @@ var ts; markAliasSymbolAsReferenced(rootSymbol); } } + function getParameterTypeNodeForDecoratorCheck(node) { + return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type; + } /** Check the decorators of a node */ function checkDecorators(node) { if (!node.decorators) { @@ -39158,7 +39236,7 @@ var ts; if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } } break; @@ -39167,11 +39245,13 @@ var ts; case 152 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; - markTypeNodeAsReferenced(parameter.type); + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markTypeNodeAsReferenced(node.type); break; case 147 /* PropertyDeclaration */: + markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; case 144 /* Parameter */: markTypeNodeAsReferenced(node.type); break; @@ -39323,6 +39403,13 @@ var ts; } } } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } function errorUnusedLocal(node, name) { if (isIdentifierThatStartsWithUnderScore(node)) { var declaration = ts.getRootDeclaration(node.parent); @@ -39332,7 +39419,9 @@ var ts; return; } } - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + if (!isRemovedPropertyFromObjectSpread(node.kind === 70 /* Identifier */ ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } } function parameterNameStartsWithUnderscore(parameterName) { return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); @@ -40472,7 +40561,7 @@ var ts; checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - if (languageVersion < 2 /* ES2015 */) { + if (languageVersion < 2 /* ES2015 */ && !ts.isInAmbientContext(node)) { checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); } var baseTypes = getBaseTypes(type); @@ -46247,10 +46336,11 @@ var ts; return undefined; } var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor; - if (accessor !== firstAccessor) { + var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined; + if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) { return undefined; } - var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators); + var decorators = firstAccessorWithDecorators.decorators; var parameters = getDecoratorsOfParameters(setAccessor); if (!decorators && !parameters) { return undefined; @@ -46291,14 +46381,14 @@ var ts; * @param node The declaration node. * @param allDecorators An object containing all of the decorators for the declaration. */ - function transformAllDecoratorsOfDeclaration(node, allDecorators) { + function transformAllDecoratorsOfDeclaration(node, container, allDecorators) { if (!allDecorators) { return undefined; } var decoratorExpressions = []; ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator)); ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter)); - addTypeMetadata(node, decoratorExpressions); + addTypeMetadata(node, container, decoratorExpressions); return decoratorExpressions; } /** @@ -46345,7 +46435,7 @@ var ts; */ function generateClassElementDecorationExpression(node, member) { var allDecorators = getAllDecoratorsOfClassElement(node, member); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -46408,7 +46498,7 @@ var ts; */ function generateConstructorDecorationExpression(node) { var allDecorators = getAllDecoratorsOfConstructor(node); - var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators); + var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators); if (!decoratorExpressions) { return undefined; } @@ -46454,35 +46544,35 @@ var ts; * @param node The declaration node. * @param decoratorExpressions The destination array to which to add new decorator expressions. */ - function addTypeMetadata(node, decoratorExpressions) { + function addTypeMetadata(node, container, decoratorExpressions) { if (USE_NEW_TYPE_METADATA_FORMAT) { - addNewTypeMetadata(node, decoratorExpressions); + addNewTypeMetadata(node, container, decoratorExpressions); } else { - addOldTypeMetadata(node, decoratorExpressions); + addOldTypeMetadata(node, container, decoratorExpressions); } } - function addOldTypeMetadata(node, decoratorExpressions) { + function addOldTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { if (shouldAddTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node))); } if (shouldAddParamTypesMetadata(node)) { - decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node))); + decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container))); } if (shouldAddReturnTypeMetadata(node)) { decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node))); } } } - function addNewTypeMetadata(node, decoratorExpressions) { + function addNewTypeMetadata(node, container, decoratorExpressions) { if (compilerOptions.emitDecoratorMetadata) { var properties = void 0; if (shouldAddTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeTypeOfNode(node)))); } if (shouldAddParamTypesMetadata(node)) { - (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node)))); + (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container)))); } if (shouldAddReturnTypeMetadata(node)) { (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node)))); @@ -46524,12 +46614,16 @@ var ts; * @param node The node to test. */ function shouldAddParamTypesMetadata(node) { - var kind = node.kind; - return kind === 226 /* ClassDeclaration */ - || kind === 197 /* ClassExpression */ - || kind === 149 /* MethodDeclaration */ - || kind === 151 /* GetAccessor */ - || kind === 152 /* SetAccessor */; + switch (node.kind) { + case 226 /* ClassDeclaration */: + case 197 /* ClassExpression */: + return ts.getFirstConstructorWithBody(node) !== undefined; + case 149 /* MethodDeclaration */: + case 151 /* GetAccessor */: + case 152 /* SetAccessor */: + return true; + } + return false; } /** * Serializes the type of a node for use with decorator type metadata. @@ -46552,29 +46646,12 @@ var ts; return ts.createVoidZero(); } } - /** - * Gets the most likely element type for a TypeNode. This is not an exhaustive test - * as it assumes a rest argument can only be an array type (either T[], or Array). - * - * @param node The type node. - */ - function getRestParameterElementType(node) { - if (node && node.kind === 162 /* ArrayType */) { - return node.elementType; - } - else if (node && node.kind === 157 /* TypeReference */) { - return ts.singleOrUndefined(node.typeArguments); - } - else { - return undefined; - } - } /** * Serializes the types of the parameters of a node for use with decorator type metadata. * * @param node The node that should have its parameter types serialized. */ - function serializeParameterTypesOfNode(node) { + function serializeParameterTypesOfNode(node, container) { var valueDeclaration = ts.isClassLike(node) ? ts.getFirstConstructorWithBody(node) : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body) @@ -46582,7 +46659,7 @@ var ts; : undefined; var expressions = []; if (valueDeclaration) { - var parameters = valueDeclaration.parameters; + var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container); var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; @@ -46590,7 +46667,7 @@ var ts; continue; } if (parameter.dotDotDotToken) { - expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type))); + expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type))); } else { expressions.push(serializeTypeOfNode(parameter)); @@ -46599,6 +46676,15 @@ var ts; } return ts.createArrayLiteral(expressions); } + function getParametersOfDecoratedDeclaration(node, container) { + if (container && node.kind === 151 /* GetAccessor */) { + var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; + if (setAccessor) { + return setAccessor.parameters; + } + } + return node.parameters; + } /** * Serializes the return type of a node for use with decorator type metadata. * @@ -50842,12 +50928,17 @@ var ts; convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; } } + startLexicalEnvironment(); var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement); + var lexicalEnvironment = endLexicalEnvironment(); var currentState = convertedLoopState; convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length) { + if (loopOutParameters.length || lexicalEnvironment) { var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); + if (loopOutParameters.length) { + copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); + } + ts.addRange(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*location*/ undefined, /*multiline*/ true); } if (!ts.isBlock(loopBody)) { @@ -54556,12 +54647,12 @@ var ts; // So the helper will be emit at the correct position instead of at the top of the source-file var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); - var updated = ts.updateSourceFileNode(node, ts.createNodeArray([ + var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.createNodeArray([ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) - ], node.statements)); + ], node.statements)), 1024 /* NoTrailingComments */); if (!(compilerOptions.outFile || compilerOptions.out)) { ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; }); } @@ -57503,7 +57594,7 @@ var ts; return; } encodeLastRecordedSourceMapSpan(); - return ts.stringify({ + return JSON.stringify({ version: 3, file: sourceMapData.sourceMapFile, sourceRoot: sourceMapData.sourceMapSourceRoot, @@ -57691,6 +57782,9 @@ var ts; } if (!skipTrailingComments) { emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true); + if (hasWrittenComment && !writer.isAtStartOfLine()) { + writer.writeLine(); + } } if (extendedDiagnostics) { ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns"); @@ -58000,6 +58094,7 @@ var ts; writer.writeSpace = writer.write; writer.writeStringLiteral = writer.writeLiteral; writer.writeParameter = writer.write; + writer.writeProperty = writer.write; writer.writeSymbol = writer.write; setWriter(writer); } @@ -63968,14 +64063,7 @@ var ts; ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; /* @internal */ function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ @@ -64259,9 +64347,10 @@ var ts; * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -64389,7 +64478,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -64566,7 +64655,7 @@ var ts; * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the @@ -64593,7 +64682,7 @@ var ts; var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (fileNames) { @@ -64790,7 +64879,9 @@ var ts; this.text = text; } StringScriptSnapshot.prototype.getText = function (start, end) { - return this.text.substring(start, end); + return start === 0 && end === this.text.length + ? this.text + : this.text.substring(start, end); }; StringScriptSnapshot.prototype.getLength = function () { return this.text.length; @@ -66063,6 +66154,7 @@ var ts; writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, writeSymbol: writeSymbol, writeLine: writeLine, increaseIndent: function () { indent++; }, @@ -67861,13 +67953,14 @@ var ts; // completion entry. var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), kind: symbolKind, displayParts: displayParts, - documentation: documentation + documentation: documentation, + tags: tags }; } } @@ -67879,7 +67972,8 @@ var ts; kind: ts.ScriptElementKind.keyword, kindModifiers: ts.ScriptElementKindModifier.none, displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined + documentation: undefined, + tags: undefined }; } return undefined; @@ -70939,6 +71033,30 @@ var ts; return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getJsDocTagsFromDeclarations(declarations) { + // Only collect doc comments from duplicate declarations once. + var tags = []; + forEachUnique(declarations, function (declaration) { + var jsDocs = ts.getJSDocs(declaration); + if (!jsDocs) { + return; + } + for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { + var doc = jsDocs_1[_i]; + var tagsForDoc = doc.tags; + if (tagsForDoc) { + tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 279 /* JSDocTag */; }).map(function (jsDocTag) { + return { + name: jsDocTag.tagName.text, + text: jsDocTag.comment + }; + })); + } + } + }); + return tags; + } + JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations; /** * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. @@ -71031,13 +71149,19 @@ var ts; var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 70 /* Identifier */ ? currentName.text : "param" + i; - docParams += indentationStr + " * @param " + paramName + newLine; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } // A doc comment consists of the following // * The opening comment line @@ -73713,7 +73837,8 @@ var ts; suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: [ts.punctuationPart(25 /* CommaToken */), ts.spacePart()], parameters: signatureHelpParameters, - documentation: candidateSignature.getDocumentationComment() + documentation: candidateSignature.getDocumentationComment(), + tags: candidateSignature.getJsDocTags() }; }); var argumentIndex = argumentListInfo.argumentIndex; @@ -73857,6 +73982,7 @@ var ts; if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; + var tags; var symbolFlags = symbol.flags; var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location); var hasAddedSymbolInfo; @@ -74161,6 +74287,7 @@ var ts; } if (!documentation) { documentation = symbol.getDocumentationComment(); + tags = symbol.getJsDocTags(); if (documentation.length === 0 && symbol.flags & 4 /* Property */) { // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. @@ -74176,6 +74303,7 @@ var ts; continue; } documentation = rhsSymbol.getDocumentationComment(); + tags = rhsSymbol.getJsDocTags(); if (documentation.length > 0) { break; } @@ -74183,7 +74311,7 @@ var ts; } } } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; function addNewLineIfDisplayPartsExist() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -74234,6 +74362,7 @@ var ts; displayParts.push(ts.punctuationPart(19 /* CloseParenToken */)); } documentation = signature.getDocumentationComment(); + tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { @@ -78257,6 +78386,12 @@ var ts; } return this.documentationComment; }; + SymbolObject.prototype.getJsDocTags = function () { + if (this.tags === undefined) { + this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations); + } + return this.tags; + }; return SymbolObject; }()); var TokenObject = (function (_super) { @@ -78340,6 +78475,12 @@ var ts; } return this.documentationComment; }; + SignatureObject.prototype.getJsDocTags = function () { + if (this.jsDocTags === undefined) { + this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : []; + } + return this.jsDocTags; + }; return SignatureObject; }()); var SourceFileObject = (function (_super) { @@ -79044,7 +79185,8 @@ var ts; kindModifiers: ts.ScriptElementKindModifier.none, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined + documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, + tags: type.symbol ? type.symbol.getJsDocTags() : undefined }; } } @@ -79056,7 +79198,8 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, - documentation: displayPartsDocumentationsAndKind.documentation + documentation: displayPartsDocumentationsAndKind.documentation, + tags: displayPartsDocumentationsAndKind.tags }; } /// Goto definition @@ -79378,7 +79521,7 @@ var ts; } var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Check if in a context where we don't want to perform any insertion - if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) { + if (ts.isInString(sourceFile, position)) { return false; } if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 3f1242014ca..66a67edf13e 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -137,7 +137,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.1.4"; + ts.version = "2.1.5"; })(ts || (ts = {})); (function (ts) { var createObject = Object.create; @@ -818,15 +818,6 @@ var ts; return result; } ts.reduceProperties = reduceProperties; - function reduceOwnProperties(map, callback, initial) { - var result = initial; - for (var key in map) - if (hasOwnProperty.call(map, key)) { - result = callback(result, map[key], String(key)); - } - return result; - } - ts.reduceOwnProperties = reduceOwnProperties; function equalOwnProperties(left, right, equalityComparer) { if (left === right) return true; @@ -1673,8 +1664,19 @@ var ts; ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; ts.supportedJavascriptExtensions = [".js", ".jsx"]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options) { - return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + function getSupportedExtensions(options, extraFileExtensions) { + var needAllExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { + var extInfo = extraFileExtensions_1[_i]; + if (needAllExtensions || extInfo.scriptKind === 3) { + extensions.push(extInfo.extension); + } + } + return extensions; } ts.getSupportedExtensions = getSupportedExtensions; function hasJavaScriptFileExtension(fileName) { @@ -1685,11 +1687,11 @@ var ts; return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); } ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions) { + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; @@ -3207,6 +3209,7 @@ var ts; JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, @@ -5291,14 +5294,7 @@ var ts; } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function parseCustomTypeOption(opt, value, errors) { - var key = trimString((value || "")).toLowerCase(); - var map = opt.type; - if (key in map) { - return map[key]; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { @@ -5538,9 +5534,10 @@ var ts; } return output; } - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) { + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } var errors = []; var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); @@ -5663,7 +5660,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -5767,7 +5764,7 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); @@ -5779,7 +5776,7 @@ var ts; exclude = validateSpecs(exclude, errors, true); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); - var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i];