diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 65e40e37f95..df9b746e9bd 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -3297,6 +3297,12 @@ + + + + + + diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 0a4a47befb9..8912f14316e 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1012,12 +1012,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T[] | ReadonlyArray)[]): T[]; + concat(...items: ConcatArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[] | ReadonlyArray)[]): T[]; + concat(...items: (T | ConcatArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1107,6 +1107,13 @@ interface ReadonlyArray { readonly [n: number]: T; } +interface ConcatArray { + readonly length: number; + readonly [n: number]: T; + join(separator?: string): string; + slice(start?: number, end?: number): T[]; +} + interface Array { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. @@ -1133,12 +1140,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T[] | ReadonlyArray)[]): T[]; + concat(...items: ConcatArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[] | ReadonlyArray)[]): T[]; + concat(...items: (T | ConcatArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 35aa9c6101f..f083f7c459b 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1012,12 +1012,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T[] | ReadonlyArray)[]): T[]; + concat(...items: ConcatArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[] | ReadonlyArray)[]): T[]; + concat(...items: (T | ConcatArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1107,6 +1107,13 @@ interface ReadonlyArray { readonly [n: number]: T; } +interface ConcatArray { + readonly length: number; + readonly [n: number]: T; + join(separator?: string): string; + slice(start?: number, end?: number): T[]; +} + interface Array { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. @@ -1133,12 +1140,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T[] | ReadonlyArray)[]): T[]; + concat(...items: ConcatArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[] | ReadonlyArray)[]): T[]; + concat(...items: (T | ConcatArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 665dad71f18..3633ed9455e 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1012,12 +1012,12 @@ interface ReadonlyArray { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T[] | ReadonlyArray)[]): T[]; + concat(...items: ConcatArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[] | ReadonlyArray)[]): T[]; + concat(...items: (T | ConcatArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. @@ -1107,6 +1107,13 @@ interface ReadonlyArray { readonly [n: number]: T; } +interface ConcatArray { + readonly length: number; + readonly [n: number]: T; + join(separator?: string): string; + slice(start?: number, end?: number): T[]; +} + interface Array { /** * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. @@ -1133,12 +1140,12 @@ interface Array { * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T[] | ReadonlyArray)[]): T[]; + concat(...items: ConcatArray[]): T[]; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ - concat(...items: (T | T[] | ReadonlyArray)[]): T[]; + concat(...items: (T | ConcatArray)[]): T[]; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. diff --git a/lib/tsc.js b/lib/tsc.js index 3c7996f3625..3558dce08db 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -132,7 +132,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -2537,7 +2537,7 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { - var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; + var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); @@ -2701,7 +2701,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } var fd; try { @@ -2883,7 +2883,7 @@ var ts; }, writeFile: function (path, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } ChakraHost.writeFile(path, data); }, @@ -3648,6 +3648,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -20117,10 +20118,8 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { - if (!ignoreDiagnostics) { - getDiagnostics(sourceFile, cancellationToken); - } + function getEmitResolver(sourceFile, cancellationToken) { + getDiagnostics(sourceFile, cancellationToken); return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -21599,6 +21598,9 @@ var ts; if (flags & 1) { nodeFlags |= 512; } + if (flags & 8) { + nodeFlags |= 16384; + } var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -21642,7 +21644,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { - return flags & 9469295; + return flags & 9469291; } function createNodeBuilder() { return { @@ -22258,7 +22260,13 @@ var ts; function createEntityNameFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216; + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); identifier.symbol = symbol; return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; @@ -22270,7 +22278,13 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216; + } var firstChar = symbolName.charCodeAt(0); var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); if (index === 0 || canUsePropertyAccess) { @@ -22363,8 +22377,14 @@ var ts; function literalTypeToString(type) { return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } + function isDefaultBindingContext(location) { + return location.kind === 269 || ts.isAmbientModule(location); + } function getNameOfSymbolAsWritten(symbol, context) { - if (context && context.flags & 4 && symbol.escapedName === "default") { + if (context && symbol.escapedName === "default" && !(context.flags & 16384) && + (!(context.flags & 16777216) || + !symbol.declarations || + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { return "default"; } if (symbol.declarations && symbol.declarations.length) { @@ -26075,7 +26095,7 @@ var ts; if (ts.isValidESSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); var links = getSymbolLinks(symbol); - return links.type || (links.type = createUniqueESSymbolType(symbol)); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); } return esSymbolType; } @@ -30576,40 +30596,29 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } function getContextualTypeForJsxExpression(node) { - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - ts.isJsxElement(node.parent) ? - node.parent.openingElement.attributes : - undefined; - if (!jsxAttributes) { - return undefined; - } - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); - } - else if (node.parent.kind === 250) { - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - return attributesType; - } + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; } function getContextualTypeForJsxAttribute(attribute) { - var attributesType = getContextualType(attribute.parent); if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return attributesType; + return getContextualType(attribute.parent); } } function getApparentTypeOfContextualType(node) { @@ -30698,7 +30707,7 @@ var ts; return getContextualTypeForJsxAttribute(parent); case 252: case 251: - return getAttributesTypeFromJsxOpeningLikeElement(parent); + return getContextualJsxElementAttributesType(parent); } return undefined; } @@ -30706,6 +30715,110 @@ var ts; node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); return node ? node.contextualMapper : identityMapper; } + function getContextualJsxElementAttributesType(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + var valueType = checkExpression(node.tagName); + if (isTypeAny(valueType)) { + return anyType; + } + var isJs = ts.isInJavaScriptFile(node); + return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + } + function getJsxSignaturesParameterTypes(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, false); + } + function getJsxSignaturesParameterTypesJs(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, true); + } + function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + if (valueType.flags & 2) { + return anyType; + } + else if (valueType.flags & 32) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = valueType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + return indexSignatureType; + } + } + return anyType; + } + var signatures = getSignaturesOfType(valueType, 1); + var ctor = true; + if (signatures.length === 0) { + signatures = getSignaturesOfType(valueType, 0); + ctor = false; + if (signatures.length === 0) { + return unknownType; + } + } + return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0); + } + function getJsxPropsTypeFromCallSignature(sig) { + var propsType = getTypeOfFirstParameterOfSignature(sig); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeFromClassType(hostClassType, isJs) { + if (isTypeAny(hostClassType)) { + return hostClassType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + return anyType; + } + else if (propsName === "") { + return hostClassType; + } + else { + var attributesType = getTypeOfPropertyOfType(hostClassType, propsName); + if (!attributesType) { + return emptyObjectType; + } + else if (isTypeAny(attributesType)) { + return attributesType; + } + else { + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getJsxPropsTypeFromConstructSignatureJs(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, true); + } + function getJsxPropsTypeFromConstructSignature(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, false); + } + function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + var hostClassType = getReturnTypeOfSignature(sig); + if (hostClassType) { + return getJsxPropsTypeFromClassType(hostClassType, isJs); + } + return getJsxPropsTypeFromCallSignature(sig); + } function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0); if (signatures.length === 1) { @@ -31099,7 +31212,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -31178,7 +31291,7 @@ var ts; } } else { - childrenTypes.push(checkExpression(child, checkMode)); + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); } } return childrenTypes; @@ -31222,7 +31335,7 @@ var ts; } return links.resolvedSymbol; } - function getJsxElementInstanceType(node, valueType, sourceAttributesType) { + function getJsxElementInstanceType(node, valueType) { ts.Debug.assert(!(valueType.flags & 131072)); if (isTypeAny(valueType)) { return anyType; @@ -31235,25 +31348,20 @@ var ts; return unknownType; } } - if (sourceAttributesType) { - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); - } + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); - } - else { - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -31280,7 +31388,7 @@ var ts; } return _jsxElementPropertiesName; } - function getJsxElementChildrenPropertyname() { + function getJsxElementChildrenPropertyName() { if (!_hasComputedJsxElementChildrenPropertyName) { _hasComputedJsxElementChildrenPropertyName = true; _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); @@ -31366,11 +31474,11 @@ var ts; } return undefined; } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType.flags & 131072) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); }), 2); } if (elementType.flags & 2) { @@ -31392,55 +31500,17 @@ var ts; } return anyType; } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); if (statelessAttributesType) { return statelessAttributesType; } - if (elementClassType && sourceAttributesType) { + if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - return anyType; - } - else if (propsName === "") { - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - return attributesType; - } - else { - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); @@ -31459,26 +31529,15 @@ var ts; } return links.resolvedJsxElementAttributesType; } - function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { - if (!sourceAttributesType) { - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); - } - return links[linkLocation]; - } - else { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); - } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, undefined, true); + return getCustomJsxElementAttributesType(node, true); } } function getAttributesTypeFromJsxOpeningLikeElement(node) { @@ -31486,7 +31545,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, undefined, false); + return getCustomJsxElementAttributesType(node, false); } } function getJsxAttributePropertySymbol(attrib) { @@ -31573,10 +31632,10 @@ var ts; return false; } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, false); + getCustomJsxElementAttributesType(openingLikeElement, false); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); } @@ -32225,9 +32284,13 @@ var ts; } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, sourceAttributesType, context) { + function inferJsxTypeArguments(signature, node, context) { + var skipContextParamType = getTypeAtPosition(signature, 0); + var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); + inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); var paramType = getTypeAtPosition(signature, 0); - inferTypes(context.inferences, sourceAttributesType, paramType); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } function inferTypeArguments(node, signature, args, excludeArgument, context) { @@ -33097,7 +33160,7 @@ var ts; var anonymousSymbol = createSymbol(2048, "__type"); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = (type.flags & 458752 && type.symbol.flags & (1536 | 3)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -34188,16 +34251,23 @@ var ts; }); return stringType; } + function getContextNode(node) { + if (node.kind === 258) { + return node.parent.parent; + } + return node; + } function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 : contextualMapper ? 2 : 3; var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; return result; } function checkExpressionCached(node, checkMode) { @@ -34225,12 +34295,9 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 393216 && !(contextualType.flags & 8)) { - var types_18 = contextualType.types; - return ts.some(types_18, function (t) { - return !(t.flags & 128 && containsType(types_18, trueType) && containsType(types_18, falseType)) && - isLiteralOfContextualType(candidateType, t); - }); + if (contextualType.flags & 393216) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } if (contextualType.flags & 1081344) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; @@ -35752,6 +35819,7 @@ var ts; } break; case 158: + case 207: break; default: ts.Debug.fail(); @@ -38441,7 +38509,7 @@ var ts; if (symbol) { if (symbol.flags & 1048576) { var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944) { + if (!prefixLocals && exportSymbol.flags & 944 && !(exportSymbol.flags & 3)) { return undefined; } symbol = exportSymbol; @@ -38905,6 +38973,8 @@ var ts; var list = augmentations_1[_d]; for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; mergeModuleAugmentation(augmentation); } } @@ -38928,6 +38998,17 @@ var ts; globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", 1); + if (augmentations) { + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -43388,14 +43469,14 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } var moduleKind = ts.getEmitModuleKind(compilerOptions); - var create = hasExportStarsToExportValues + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) && moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext; @@ -44518,6 +44599,34 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + function getNamedImportCount(node) { + if (!(node.importClause && node.importClause.namedBindings)) + return 0; + var names = node.importClause.namedBindings; + if (!names) + return 0; + if (!ts.isNamedImports(names)) + return 0; + return names.elements.length; + } + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName && e.propertyName.escapedText === "default"; + } + function getImportNeedsImportStarHelper(node) { + return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { var externalImports = []; var exportSpecifiers = ts.createMultiMap(); @@ -44527,11 +44636,13 @@ var ts; var hasExportDefault = false; var exportEquals = undefined; var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { case 239: externalImports.push(node); + hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; case 238: if (node.moduleReference.kind === 249) { @@ -44616,7 +44727,7 @@ var ts; break; } } - var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); @@ -47207,7 +47318,7 @@ var ts; if (statement.kind === 217 && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); } return ts.visitEachChild(node, visitor, context); } @@ -49735,26 +49846,31 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97) { - ts.setEmitFlags(thisArg, 4); + if (node.transformFlags & 524288 || + node.expression.kind === 97 || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 97) { + ts.setEmitFlags(thisArg, 4); + } + var resultingCall = void 0; + if (node.transformFlags & 524288) { + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + } + else { + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + } + if (node.expression.kind === 97) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); } - var resultingCall; - if (node.transformFlags & 524288) { - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); - } - else { - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); - } - if (node.expression.kind === 97) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4); - var initializer = ts.createLogicalOr(resultingCall, actualThis); - resultingCall = assignToCapturedThis - ? ts.createAssignment(ts.createIdentifier("_this"), initializer) - : initializer; - } - return ts.setOriginalNode(resultingCall, node); + return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (node.transformFlags & 524288) { @@ -52089,11 +52205,11 @@ var ts; if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864) { return innerExpr; } - if (ts.getNamespaceDeclarationNode(node)) { + if (ts.getImportNeedsImportStarHelper(node)) { context.requestEmitHelper(importStarHelper); return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]); } - if (ts.isDefaultImport(node)) { + if (ts.getImportNeedsImportDefaultHelper(node)) { context.requestEmitHelper(importDefaultHelper); return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]); } @@ -54622,7 +54738,7 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4096 | 8 | 4 | + var format = 4096 | 8 | 2048 | (shouldUseResolverType ? 131072 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); @@ -54637,7 +54753,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048, writer); errorNameNode = undefined; } } @@ -54867,7 +54983,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048, writer); write(";"); writeLine(); return tempVarName; @@ -56122,7 +56238,7 @@ var ts; }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { if (!emitOnlyDtsFiles) { printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); } @@ -59780,7 +59896,7 @@ var ts; } } } - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -60574,6 +60690,14 @@ var ts; if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } + if (options.emitDeclarationOnly) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); @@ -60593,7 +60717,9 @@ var ts; var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); } @@ -61724,21 +61850,24 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { - if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && + !options.extendedDiagnostics && + !options.diagnostics) { system.clearScreen(); } } function createWatchStatusReporter(system, pretty) { return pretty ? - function (diagnostic, newLine) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic); + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); system.write(output); } : - function (diagnostic, newLine) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic); + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = new Date().toLocaleTimeString() + " - "; output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); system.write(output); @@ -62134,7 +62263,7 @@ var ts; } function reportWatchDiagnostic(message) { if (host.onWatchStatusChange) { - host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions); } } function scheduleProgramUpdate() { @@ -62461,6 +62590,12 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, { name: "sourceMap", type: "boolean", @@ -63501,7 +63636,7 @@ var ts; return x === undefined || x === null; } function directoryOfCombinedPath(fileName, basePath) { - return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } @@ -63509,8 +63644,7 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; @@ -63590,19 +63724,19 @@ var ts; function isSuccessfulParsedTsconfig(value) { return !!value.options; } - function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); return { raw: json || convertToObject(sourceFile, errors) }; } var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); if (ownConfig.extendedConfigPath) { resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; @@ -63623,7 +63757,7 @@ var ts; } return ownConfig; } - function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } @@ -63637,12 +63771,12 @@ var ts; } else { var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { var options = getDefaultCompilerOptions(configFileName); var typeAcquisition, typingOptionstypeAcquisition; var extendedConfigPath; @@ -63660,7 +63794,7 @@ var ts; switch (key) { case "extends": var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -63694,13 +63828,13 @@ var ts; } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { @@ -63710,7 +63844,7 @@ var ts; } return extendedConfigPath; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -63720,12 +63854,12 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; var mapPropertiesInRawIfNotUndefined = function (propertyName) { if (raw_2[propertyName]) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 71285783487..b1e7873eb91 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -511,7 +511,6 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; @@ -533,13 +532,13 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors"; NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; @@ -557,7 +556,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -565,6 +564,7 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); var SymbolAccessibility; (function (SymbolAccessibility) { @@ -821,6 +821,7 @@ var ts; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; @@ -1302,7 +1303,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -3721,7 +3722,7 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { - var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; + var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); @@ -3885,7 +3886,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } var fd; try { @@ -4072,7 +4073,7 @@ var ts; }, writeFile: function (path, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } ChakraHost.writeFile(path, data); }, @@ -4837,6 +4838,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -21510,10 +21512,8 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { - if (!ignoreDiagnostics) { - getDiagnostics(sourceFile, cancellationToken); - } + function getEmitResolver(sourceFile, cancellationToken) { + getDiagnostics(sourceFile, cancellationToken); return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -22992,6 +22992,9 @@ var ts; if (flags & 1) { nodeFlags |= 512; } + if (flags & 8) { + nodeFlags |= 16384; + } var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -23035,7 +23038,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { - return flags & 9469295; + return flags & 9469291; } function createNodeBuilder() { return { @@ -23651,7 +23654,13 @@ var ts; function createEntityNameFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216; + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); identifier.symbol = symbol; return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; @@ -23663,7 +23672,13 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216; + } var firstChar = symbolName.charCodeAt(0); var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); if (index === 0 || canUsePropertyAccess) { @@ -23756,8 +23771,14 @@ var ts; function literalTypeToString(type) { return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } + function isDefaultBindingContext(location) { + return location.kind === 269 || ts.isAmbientModule(location); + } function getNameOfSymbolAsWritten(symbol, context) { - if (context && context.flags & 4 && symbol.escapedName === "default") { + if (context && symbol.escapedName === "default" && !(context.flags & 16384) && + (!(context.flags & 16777216) || + !symbol.declarations || + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { return "default"; } if (symbol.declarations && symbol.declarations.length) { @@ -27468,7 +27489,7 @@ var ts; if (ts.isValidESSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); var links = getSymbolLinks(symbol); - return links.type || (links.type = createUniqueESSymbolType(symbol)); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); } return esSymbolType; } @@ -31969,40 +31990,29 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } function getContextualTypeForJsxExpression(node) { - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - ts.isJsxElement(node.parent) ? - node.parent.openingElement.attributes : - undefined; - if (!jsxAttributes) { - return undefined; - } - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); - } - else if (node.parent.kind === 250) { - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - return attributesType; - } + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; } function getContextualTypeForJsxAttribute(attribute) { - var attributesType = getContextualType(attribute.parent); if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return attributesType; + return getContextualType(attribute.parent); } } function getApparentTypeOfContextualType(node) { @@ -32091,7 +32101,7 @@ var ts; return getContextualTypeForJsxAttribute(parent); case 252: case 251: - return getAttributesTypeFromJsxOpeningLikeElement(parent); + return getContextualJsxElementAttributesType(parent); } return undefined; } @@ -32099,6 +32109,110 @@ var ts; node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); return node ? node.contextualMapper : identityMapper; } + function getContextualJsxElementAttributesType(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + var valueType = checkExpression(node.tagName); + if (isTypeAny(valueType)) { + return anyType; + } + var isJs = ts.isInJavaScriptFile(node); + return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + } + function getJsxSignaturesParameterTypes(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, false); + } + function getJsxSignaturesParameterTypesJs(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, true); + } + function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + if (valueType.flags & 2) { + return anyType; + } + else if (valueType.flags & 32) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = valueType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + return indexSignatureType; + } + } + return anyType; + } + var signatures = getSignaturesOfType(valueType, 1); + var ctor = true; + if (signatures.length === 0) { + signatures = getSignaturesOfType(valueType, 0); + ctor = false; + if (signatures.length === 0) { + return unknownType; + } + } + return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0); + } + function getJsxPropsTypeFromCallSignature(sig) { + var propsType = getTypeOfFirstParameterOfSignature(sig); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeFromClassType(hostClassType, isJs) { + if (isTypeAny(hostClassType)) { + return hostClassType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + return anyType; + } + else if (propsName === "") { + return hostClassType; + } + else { + var attributesType = getTypeOfPropertyOfType(hostClassType, propsName); + if (!attributesType) { + return emptyObjectType; + } + else if (isTypeAny(attributesType)) { + return attributesType; + } + else { + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getJsxPropsTypeFromConstructSignatureJs(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, true); + } + function getJsxPropsTypeFromConstructSignature(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, false); + } + function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + var hostClassType = getReturnTypeOfSignature(sig); + if (hostClassType) { + return getJsxPropsTypeFromClassType(hostClassType, isJs); + } + return getJsxPropsTypeFromCallSignature(sig); + } function getContextualCallSignature(type, node) { var signatures = getSignaturesOfType(type, 0); if (signatures.length === 1) { @@ -32492,7 +32606,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -32571,7 +32685,7 @@ var ts; } } else { - childrenTypes.push(checkExpression(child, checkMode)); + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); } } return childrenTypes; @@ -32615,7 +32729,7 @@ var ts; } return links.resolvedSymbol; } - function getJsxElementInstanceType(node, valueType, sourceAttributesType) { + function getJsxElementInstanceType(node, valueType) { ts.Debug.assert(!(valueType.flags & 131072)); if (isTypeAny(valueType)) { return anyType; @@ -32628,25 +32742,20 @@ var ts; return unknownType; } } - if (sourceAttributesType) { - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); - } + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); - } - else { - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2); } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -32673,7 +32782,7 @@ var ts; } return _jsxElementPropertiesName; } - function getJsxElementChildrenPropertyname() { + function getJsxElementChildrenPropertyName() { if (!_hasComputedJsxElementChildrenPropertyName) { _hasComputedJsxElementChildrenPropertyName = true; _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); @@ -32759,11 +32868,11 @@ var ts; } return undefined; } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType.flags & 131072) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); }), 2); } if (elementType.flags & 2) { @@ -32785,55 +32894,17 @@ var ts; } return anyType; } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); if (statelessAttributesType) { return statelessAttributesType; } - if (elementClassType && sourceAttributesType) { + if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - return anyType; - } - else if (propsName === "") { - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - return attributesType; - } - else { - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); @@ -32852,26 +32923,15 @@ var ts; } return links.resolvedJsxElementAttributesType; } - function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { - if (!sourceAttributesType) { - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); - } - return links[linkLocation]; - } - else { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); - } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } function getAllAttributesTypeFromJsxOpeningLikeElement(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, undefined, true); + return getCustomJsxElementAttributesType(node, true); } } function getAttributesTypeFromJsxOpeningLikeElement(node) { @@ -32879,7 +32939,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, undefined, false); + return getCustomJsxElementAttributesType(node, false); } } function getJsxAttributePropertySymbol(attrib) { @@ -32966,10 +33026,10 @@ var ts; return false; } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement, checkMode) { - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, false); + getCustomJsxElementAttributesType(openingLikeElement, false); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); } @@ -33618,9 +33678,13 @@ var ts; } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, sourceAttributesType, context) { + function inferJsxTypeArguments(signature, node, context) { + var skipContextParamType = getTypeAtPosition(signature, 0); + var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); + inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); var paramType = getTypeAtPosition(signature, 0); - inferTypes(context.inferences, sourceAttributesType, paramType); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } function inferTypeArguments(node, signature, args, excludeArgument, context) { @@ -34490,7 +34554,7 @@ var ts; var anonymousSymbol = createSymbol(2048, "__type"); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = (type.flags & 458752 && type.symbol.flags & (1536 | 3)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -35581,16 +35645,23 @@ var ts; }); return stringType; } + function getContextNode(node) { + if (node.kind === 258) { + return node.parent.parent; + } + return node; + } function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 : contextualMapper ? 2 : 3; var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; return result; } function checkExpressionCached(node, checkMode) { @@ -35618,12 +35689,9 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 393216 && !(contextualType.flags & 8)) { - var types_18 = contextualType.types; - return ts.some(types_18, function (t) { - return !(t.flags & 128 && containsType(types_18, trueType) && containsType(types_18, falseType)) && - isLiteralOfContextualType(candidateType, t); - }); + if (contextualType.flags & 393216) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } if (contextualType.flags & 1081344) { var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; @@ -37159,6 +37227,7 @@ var ts; } break; case 158: + case 207: break; default: ts.Debug.fail(); @@ -39848,7 +39917,7 @@ var ts; if (symbol) { if (symbol.flags & 1048576) { var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944) { + if (!prefixLocals && exportSymbol.flags & 944 && !(exportSymbol.flags & 3)) { return undefined; } symbol = exportSymbol; @@ -40312,6 +40381,8 @@ var ts; var list = augmentations_1[_d]; for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; mergeModuleAugmentation(augmentation); } } @@ -40335,6 +40406,17 @@ var ts; globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", 1); + if (augmentations) { + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -44809,14 +44891,14 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } var moduleKind = ts.getEmitModuleKind(compilerOptions); - var create = hasExportStarsToExportValues + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) && moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext; @@ -45939,6 +46021,34 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + function getNamedImportCount(node) { + if (!(node.importClause && node.importClause.namedBindings)) + return 0; + var names = node.importClause.namedBindings; + if (!names) + return 0; + if (!ts.isNamedImports(names)) + return 0; + return names.elements.length; + } + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName && e.propertyName.escapedText === "default"; + } + function getImportNeedsImportStarHelper(node) { + return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { var externalImports = []; var exportSpecifiers = ts.createMultiMap(); @@ -45948,11 +46058,13 @@ var ts; var hasExportDefault = false; var exportEquals = undefined; var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { case 239: externalImports.push(node); + hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; case 238: if (node.moduleReference.kind === 249) { @@ -46037,7 +46149,7 @@ var ts; break; } } - var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); @@ -48663,7 +48775,7 @@ var ts; if (statement.kind === 217 && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); } return ts.visitEachChild(node, visitor, context); } @@ -51260,26 +51372,31 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97) { - ts.setEmitFlags(thisArg, 4); + if (node.transformFlags & 524288 || + node.expression.kind === 97 || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 97) { + ts.setEmitFlags(thisArg, 4); + } + var resultingCall = void 0; + if (node.transformFlags & 524288) { + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + } + else { + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + } + if (node.expression.kind === 97) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); } - var resultingCall; - if (node.transformFlags & 524288) { - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); - } - else { - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); - } - if (node.expression.kind === 97) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4); - var initializer = ts.createLogicalOr(resultingCall, actualThis); - resultingCall = assignToCapturedThis - ? ts.createAssignment(ts.createIdentifier("_this"), initializer) - : initializer; - } - return ts.setOriginalNode(resultingCall, node); + return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { if (node.transformFlags & 524288) { @@ -53659,11 +53776,11 @@ var ts; if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864) { return innerExpr; } - if (ts.getNamespaceDeclarationNode(node)) { + if (ts.getImportNeedsImportStarHelper(node)) { context.requestEmitHelper(importStarHelper); return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]); } - if (ts.isDefaultImport(node)) { + if (ts.getImportNeedsImportDefaultHelper(node)) { context.requestEmitHelper(importDefaultHelper); return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]); } @@ -55591,7 +55708,7 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4096 | 8 | 4 | + var format = 4096 | 8 | 2048 | (shouldUseResolverType ? 131072 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); @@ -55606,7 +55723,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048, writer); errorNameNode = undefined; } } @@ -55836,7 +55953,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048, writer); write(";"); writeLine(); return tempVarName; @@ -57704,7 +57821,7 @@ var ts; }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { if (!emitOnlyDtsFiles) { printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); } @@ -61092,7 +61209,7 @@ var ts; } } } - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -61886,6 +62003,14 @@ var ts; if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } + if (options.emitDeclarationOnly) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); @@ -61905,7 +62030,9 @@ var ts; var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); } @@ -62251,6 +62378,12 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, { name: "sourceMap", type: "boolean", @@ -63291,7 +63424,7 @@ var ts; return x === undefined || x === null; } function directoryOfCombinedPath(fileName, basePath) { - return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } @@ -63299,8 +63432,7 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; @@ -63380,19 +63512,19 @@ var ts; function isSuccessfulParsedTsconfig(value) { return !!value.options; } - function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); return { raw: json || convertToObject(sourceFile, errors) }; } var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); if (ownConfig.extendedConfigPath) { resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; @@ -63413,7 +63545,7 @@ var ts; } return ownConfig; } - function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } @@ -63427,12 +63559,12 @@ var ts; } else { var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { var options = getDefaultCompilerOptions(configFileName); var typeAcquisition, typingOptionstypeAcquisition; var extendedConfigPath; @@ -63450,7 +63582,7 @@ var ts; switch (key) { case "extends": var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -63484,13 +63616,13 @@ var ts; } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { @@ -63500,7 +63632,7 @@ var ts; } return extendedConfigPath; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -63510,12 +63642,12 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; var mapPropertiesInRawIfNotUndefined = function (propertyName) { if (raw_2[propertyName]) { @@ -65125,7 +65257,7 @@ var ts; ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; @@ -66548,14 +66680,14 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (pathCompletion) { - if (!result.some(function (entry) { return entry.name === pathCompletion; })) { - result.push(createCompletionEntryForModule(pathCompletion, "external module name", span)); + var _loop_7 = function (name, kind) { + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(createCompletionEntryForModule(name, kind, span)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var pathCompletion = _a[_i]; - _loop_7(pathCompletion); + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_7(name, kind); } } } @@ -66569,19 +66701,19 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { - var moduleName = _c[_b]; + for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { + var moduleName = _d[_c]; result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } return result; } function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { - return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" }] : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); if (!ts.startsWith(fragment, pathPrefix)) { - return ts.emptyArray; + return [{ name: pathPrefix, kind: "directory" }]; } var remainingFragment = fragment.slice(pathPrefix.length); return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); @@ -66603,18 +66735,21 @@ var ts; var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); - var directories = tryGetDirectories(host, baseDirectory); - return ts.mapDefined(ts.concatenate(matches, directories), function (match) { - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - return; - } - var start = completePrefix.length; - var length = normalizedMatch.length - start - normalizedSuffix.length; - return ts.removeFileExtension(normalizedMatch.substr(start, length)); + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" }); }); + var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" }); }); + return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { + var name = _a.name, kind = _a.kind; + var normalizedMatch = ts.normalizePath(name); + var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); + return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; }); } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; @@ -66799,15 +66934,19 @@ var ts; return false; } function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); + if (path === "./" || path === ".\\") { + return ""; + } + var norm = ts.normalizePath(path); + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; } var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* previousToken.end); + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153; @@ -69013,6 +69168,11 @@ var ts; if (namedBindings && namedBindings.kind === 241) { handleNamespaceImport(direct, namedBindings.name); } + else if (ts.isDefaultImport(direct)) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); + addIndirectUser(sourceFileLike); + directImports.push(direct); + } else { directImports.push(direct); } @@ -73362,6 +73522,7 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + var signatureHelpNodeBuilderFlags = 8192 | 3112960; function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0; @@ -73384,9 +73545,8 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var flags = 8192 | 3112960; - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); @@ -73434,7 +73594,7 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 | 3112960); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); printer.writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index cd1b577b711..4f691a39e42 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1799,7 +1799,6 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, - WriteDefaultSymbolWithoutName = 4, UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, @@ -1821,12 +1820,12 @@ declare namespace ts { IgnoreErrors = 3112960, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, + InInitialEntityName = 16777216, } enum TypeFormatFlags { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, - WriteDefaultSymbolWithoutName = 4, UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, @@ -1844,13 +1843,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469295, + NodeBuilderFlagsMask = 9469291, } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, + UseAliasDefinedOutsideCurrentScope = 8, } /** * @deprecated @@ -2192,6 +2192,7 @@ declare namespace ts { isFixed: boolean; } enum InferenceFlags { + None = 0, InferUnionTypes = 1, NoDefault = 2, AnyDefault = 4, @@ -2266,6 +2267,7 @@ declare namespace ts { charset?: string; checkJs?: boolean; declaration?: boolean; + emitDeclarationOnly?: boolean; declarationDir?: string; disableSizeLimit?: boolean; downlevelIteration?: boolean; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index e879b3dd068..73a1835a5e0 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -575,7 +575,7 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + // empty space NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; // empty space NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; @@ -600,6 +600,7 @@ var ts; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -607,7 +608,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + // hole because there's a hole in node builder flags TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; // hole because there's a hole in node builder flags TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; @@ -632,7 +633,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -648,6 +649,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; // Build symbol name using any nodes needed, instead of just components of an entity name SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -940,6 +943,7 @@ var ts; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; @@ -1511,7 +1515,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -4333,7 +4337,10 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { - var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); @@ -4526,7 +4533,7 @@ var ts; function writeFile(fileName, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } var fd; try { @@ -4724,7 +4731,7 @@ var ts; writeFile: function (path, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } ChakraHost.writeFile(path, data); }, @@ -5497,6 +5504,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -20059,6 +20067,12 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, { name: "sourceMap", type: "boolean", @@ -21193,9 +21207,9 @@ var ts; return x === undefined || x === null; } function directoryOfCombinedPath(fileName, basePath) { - // Use the `identity` function to avoid canonicalizing the path, as it must remain noncanonical + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical // until consistient casing errors are reported - return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } /** * Parse the contents of a config file from json or json source file (tsconfig.json). @@ -21212,8 +21226,7 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; @@ -21299,20 +21312,20 @@ var ts; * This *just* extracts options/include/exclude/files out of a config file. * It does *not* resolve the included files. */ - function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); return { raw: json || convertToObject(sourceFile, errors) }; } var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; @@ -21334,7 +21347,7 @@ var ts; } return ownConfig; } - function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } @@ -21350,12 +21363,12 @@ var ts; } else { var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { var options = getDefaultCompilerOptions(configFileName); var typeAcquisition, typingOptionstypeAcquisition; var extendedConfigPath; @@ -21373,7 +21386,7 @@ var ts; switch (key) { case "extends": var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -21407,14 +21420,14 @@ var ts; } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { @@ -21424,7 +21437,7 @@ var ts; } return extendedConfigPath; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -21434,13 +21447,13 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; var mapPropertiesInRawIfNotUndefined = function (propertyName) { if (raw_2[propertyName]) { @@ -27102,12 +27115,10 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { + function getEmitResolver(sourceFile, cancellationToken) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - if (!ignoreDiagnostics) { - getDiagnostics(sourceFile, cancellationToken); - } + getDiagnostics(sourceFile, cancellationToken); return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -28873,6 +28884,9 @@ var ts; if (flags & 1 /* WriteTypeParametersOrArguments */) { nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -28916,7 +28930,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { - return flags & 9469295 /* NodeBuilderFlagsMask */; + return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -29561,7 +29575,13 @@ var ts; function createEntityNameFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); identifier.symbol = symbol; return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; @@ -29573,7 +29593,13 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } var firstChar = symbolName.charCodeAt(0); var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); if (index === 0 || canUsePropertyAccess) { @@ -29666,6 +29692,9 @@ var ts; function literalTypeToString(type) { return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } + function isDefaultBindingContext(location) { + return location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location); + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -29674,7 +29703,13 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { - if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { return "default"; } if (symbol.declarations && symbol.declarations.length) { @@ -33932,7 +33967,7 @@ var ts; if (ts.isValidESSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); var links = getSymbolLinks(symbol); - return links.type || (links.type = createUniqueESSymbolType(symbol)); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); } return esSymbolType; } @@ -39197,50 +39232,33 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } function getContextualTypeForJsxExpression(node) { - // JSX expression can appear in two position : JSX Element's children or JSX attribute - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - ts.isJsxElement(node.parent) ? - node.parent.openingElement.attributes : - undefined; // node.parent is JsxFragment with no attributes - if (!jsxAttributes) { - return undefined; // don't check children of a fragment - } - // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type - // which is a type of the parameter of the signature we are trying out. - // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - // JSX expression is in JSX attribute - return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); - } - else if (node.parent.kind === 250 /* JsxElement */) { - // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - // JSX expression is in JSX spread attribute - return attributesType; - } + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; } function getContextualTypeForJsxAttribute(attribute) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(attribute.parent); if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return attributesType; + return getContextualType(attribute.parent); } } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily @@ -39351,7 +39369,7 @@ var ts; return getContextualTypeForJsxAttribute(parent); case 252 /* JsxOpeningElement */: case 251 /* JsxSelfClosingElement */: - return getAttributesTypeFromJsxOpeningLikeElement(parent); + return getContextualJsxElementAttributesType(parent); } return undefined; } @@ -39359,6 +39377,124 @@ var ts; node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); return node ? node.contextualMapper : identityMapper; } + function getContextualJsxElementAttributesType(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + var valueType = checkExpression(node.tagName); + if (isTypeAny(valueType)) { + // Short-circuit if the class tag is using an element type 'any' + return anyType; + } + var isJs = ts.isInJavaScriptFile(node); + return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + } + function getJsxSignaturesParameterTypes(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false); + } + function getJsxSignaturesParameterTypesJs(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true); + } + function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type + if (valueType.flags & 2 /* String */) { + return anyType; + } + else if (valueType.flags & 32 /* StringLiteral */) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = valueType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + } + return anyType; + } + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(valueType, 1 /* Construct */); + var ctor = true; + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(valueType, 0 /* Call */); + ctor = false; + if (signatures.length === 0) { + // We found no signatures at all, which is an error + return unknownType; + } + } + return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */); + } + function getJsxPropsTypeFromCallSignature(sig) { + var propsType = getTypeOfFirstParameterOfSignature(sig); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeFromClassType(hostClassType, isJs) { + if (isTypeAny(hostClassType)) { + return hostClassType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + // There is no type ElementAttributesProperty, return 'any' + return anyType; + } + else if (propsName === "") { + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + return hostClassType; + } + else { + var attributesType = getTypeOfPropertyOfType(hostClassType, propsName); + if (!attributesType) { + // There is no property named 'props' on this instance type + return emptyObjectType; + } + else if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getJsxPropsTypeFromConstructSignatureJs(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true); + } + function getJsxPropsTypeFromConstructSignature(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false); + } + function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + var hostClassType = getReturnTypeOfSignature(sig); + if (hostClassType) { + return getJsxPropsTypeFromClassType(hostClassType, isJs); + } + return getJsxPropsTypeFromCallSignature(sig); + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { @@ -39837,7 +39973,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -39929,7 +40065,7 @@ var ts; } } else { - childrenTypes.push(checkExpression(child, checkMode)); + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); } } return childrenTypes; @@ -39992,7 +40128,7 @@ var ts; * element is not a class element, or the class element type cannot be determined, returns 'undefined'. * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ - function getJsxElementInstanceType(node, valueType, sourceAttributesType) { + function getJsxElementInstanceType(node, valueType) { ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' @@ -40009,27 +40145,21 @@ var ts; return unknownType; } } - if (sourceAttributesType) { - // Instantiate in context of source type - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); - } + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -40074,7 +40204,7 @@ var ts; } return _jsxElementPropertiesName; } - function getJsxElementChildrenPropertyname() { + function getJsxElementChildrenPropertyName() { if (!_hasComputedJsxElementChildrenPropertyName) { _hasComputedJsxElementChildrenPropertyName = true; _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); @@ -40204,11 +40334,11 @@ var ts; * anyType if there is no type ElementAttributesProperty or there is an error * emptyObjectType if there is no "prop" in the element instance type */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); }), 2 /* Subtype */); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type @@ -40237,7 +40367,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -40247,53 +40377,10 @@ var ts; return statelessAttributesType; } // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType && sourceAttributesType) { + if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - // There is no type ElementAttributesProperty, return 'any' - return anyType; - } - else if (propsName === "") { - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - // There is no property named 'props' on this instance type - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - // Props is of type 'any' or unknown - return attributesType; - } - else { - // Normal case -- add in IntrinsicClassElements and IntrinsicElements - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -40323,20 +40410,8 @@ var ts; * @param node a custom JSX opening-like element * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component */ - function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { - if (!sourceAttributesType) { - // This ensures we cache non-inference uses of this calculation (ie, contextual types or services) - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); - } - return links[linkLocation]; - } - else { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); - } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -40350,7 +40425,7 @@ var ts; else { // Because in language service, the given JSX opening-like element may be incomplete and therefore, // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ true); + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); } } /** @@ -40363,7 +40438,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ false); + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); } } /** @@ -40489,14 +40564,14 @@ var ts; // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. // 3. Check if the two are assignable to each other + // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, /*shouldIncludeAllStatelessAttributesType*/ false); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { @@ -41273,9 +41348,15 @@ var ts; } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, sourceAttributesType, context) { + function inferJsxTypeArguments(signature, node, context) { + // Skip context sensitive pass + var skipContextParamType = getTypeAtPosition(signature, 0); + var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); + inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); + // Standard pass var paramType = getTypeAtPosition(signature, 0); - inferTypes(context.inferences, sourceAttributesType, paramType); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } function inferTypeArguments(node, signature, args, excludeArgument, context) { @@ -41947,7 +42028,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : undefined; while (true) { candidate = originalCandidate; @@ -42503,7 +42584,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -43736,16 +43817,23 @@ var ts; }); return stringType; } + function getContextNode(node) { + if (node.kind === 258 /* JsxAttributes */) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; return result; } function checkExpressionCached(node, checkMode) { @@ -43776,14 +43864,9 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 393216 /* UnionOrIntersection */ && !(contextualType.flags & 8 /* Boolean */)) { - // If the contextual type is a union containing both of the 'true' and 'false' types we - // don't consider it a literal context for boolean literals. - var types_18 = contextualType.types; - return ts.some(types_18, function (t) { - return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_18, trueType) && containsType(types_18, falseType)) && - isLiteralOfContextualType(candidateType, t); - }); + if (contextualType.flags & 393216 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } if (contextualType.flags & 1081344 /* TypeVariable */) { // If the contextual type is a type variable constrained to a primitive type, consider @@ -45632,6 +45715,7 @@ var ts; } break; case 158 /* IndexSignature */: + case 207 /* SemicolonClassElement */: // Can't be private break; default: @@ -48824,7 +48908,7 @@ var ts; // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the // kinds that we do NOT prefix. var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { return undefined; } symbol = exportSymbol; @@ -49354,13 +49438,21 @@ var ts; }); } } + // We do global augmentations seperately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. if (augmentations) { - // merge module augmentations. + // merge _global_ module augmentations. // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { var list = augmentations_1[_d]; for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; mergeModuleAugmentation(augmentation); } } @@ -49387,6 +49479,19 @@ var ts; globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -54373,14 +54478,14 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } var moduleKind = ts.getEmitModuleKind(compilerOptions); - var create = hasExportStarsToExportValues + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) && moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext; @@ -55716,6 +55821,34 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + function getNamedImportCount(node) { + if (!(node.importClause && node.importClause.namedBindings)) + return 0; + var names = node.importClause.namedBindings; + if (!names) + return 0; + if (!ts.isNamedImports(names)) + return 0; + return names.elements.length; + } + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + } + function getImportNeedsImportStarHelper(node) { + return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { var externalImports = []; var exportSpecifiers = ts.createMultiMap(); @@ -55725,6 +55858,7 @@ var ts; var hasExportDefault = false; var exportEquals = undefined; var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { @@ -55734,6 +55868,7 @@ var ts; // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); + hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; case 238 /* ImportEqualsDeclaration */: if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { @@ -55827,7 +55962,7 @@ var ts; break; } } - var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); @@ -59896,7 +60031,7 @@ var ts; if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); } return ts.visitEachChild(node, visitor, context); } @@ -63447,49 +63582,54 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { - ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + if (node.transformFlags & 524288 /* ContainsSpread */ || + node.expression.kind === 97 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 97 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 524288 /* ContainsSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 97 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); } - var resultingCall; - if (node.transformFlags & 524288 /* ContainsSpread */) { - // [source] - // f(...a, b) - // x.m(...a, b) - // super(...a, b) - // super.m(...a, b) // in static - // super.m(...a, b) // in instance - // - // [output] - // f.apply(void 0, a.concat([b])) - // (_a = x).m.apply(_a, a.concat([b])) - // _super.apply(this, a.concat([b])) - // _super.m.apply(this, a.concat([b])) - // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); - } - else { - // [source] - // super(a) - // super.m(a) // in static - // super.m(a) // in instance - // - // [output] - // _super.call(this, a) - // _super.m.call(this, a) - // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), - /*location*/ node); - } - if (node.expression.kind === 97 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); - resultingCall = assignToCapturedThis - ? ts.createAssignment(ts.createIdentifier("_this"), initializer) - : initializer; - } - return ts.setOriginalNode(resultingCall, node); + return ts.visitEachChild(node, visitor, context); } /** * Visits a NewExpression that contains a spread element. @@ -67265,11 +67405,11 @@ var ts; if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { return innerExpr; } - if (ts.getNamespaceDeclarationNode(node)) { + if (ts.getImportNeedsImportStarHelper(node)) { context.requestEmitHelper(importStarHelper); return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); } - if (ts.isDefaultImport(node)) { + if (ts.getImportNeedsImportDefaultHelper(node)) { context.requestEmitHelper(importDefaultHelper); return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); } @@ -70222,7 +70362,7 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); @@ -70238,7 +70378,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -70476,7 +70616,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; @@ -72597,7 +72737,7 @@ var ts; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; // Make sure not to write js file and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { if (!emitOnlyDtsFiles) { printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); } @@ -76408,7 +76548,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -77295,6 +77435,14 @@ var ts; if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } + if (options.emitDeclarationOnly) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); @@ -77315,7 +77463,9 @@ var ts; var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); } @@ -78941,7 +79091,7 @@ var ts; ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; @@ -80673,15 +80823,15 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (pathCompletion) { + var _loop_7 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === pathCompletion; })) { - result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(createCompletionEntryForModule(name, kind, span)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var pathCompletion = _a[_i]; - _loop_7(pathCompletion); + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_7(name, kind); } } } @@ -80695,8 +80845,8 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { - var moduleName = _c[_b]; + for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { + var moduleName = _d[_c]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; @@ -80704,11 +80854,11 @@ var ts; function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" /* directory */ }] : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); if (!ts.startsWith(fragment, pathPrefix)) { - return ts.emptyArray; + return [{ name: pathPrefix, kind: "directory" /* directory */ }]; } var remainingFragment = fragment.slice(pathPrefix.length); return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); @@ -80737,19 +80887,22 @@ var ts; // that encodes the suffix, but we would have to escape the character "?" which readDirectory // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - var directories = tryGetDirectories(host, baseDirectory); + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); }); + var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); }); // Trim away prefix and suffix - return ts.mapDefined(ts.concatenate(matches, directories), function (match) { - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - return; - } - var start = completePrefix.length; - var length = normalizedMatch.length - start - normalizedSuffix.length; - return ts.removeFileExtension(normalizedMatch.substr(start, length)); + return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { + var name = _a.name, kind = _a.kind; + var normalizedMatch = ts.normalizePath(name); + var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); + return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; }); } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); @@ -80946,7 +81099,13 @@ var ts; return false; } function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); + if (path === "./" || path === ".\\") { + // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. + // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. + return ""; + } + var norm = ts.normalizePath(path); + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used @@ -80963,10 +81122,10 @@ var ts; var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* previousToken.end); + // If `contextToken !== previousToken`, this is `class C ex/**/`. + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; @@ -83569,6 +83746,11 @@ var ts; if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name); } + else if (ts.isDefaultImport(direct)) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); + addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + directImports.push(direct); + } else { directImports.push(direct); } @@ -88791,6 +88973,7 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; @@ -88813,9 +88996,8 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); @@ -88863,7 +89045,7 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 3cbca96f8fa..b361d7b0ddb 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1799,7 +1799,6 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, - WriteDefaultSymbolWithoutName = 4, UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, @@ -1821,12 +1820,12 @@ declare namespace ts { IgnoreErrors = 3112960, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, + InInitialEntityName = 16777216, } enum TypeFormatFlags { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, - WriteDefaultSymbolWithoutName = 4, UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, @@ -1844,13 +1843,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469295, + NodeBuilderFlagsMask = 9469291, } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, + UseAliasDefinedOutsideCurrentScope = 8, } /** * @deprecated @@ -2192,6 +2192,7 @@ declare namespace ts { isFixed: boolean; } enum InferenceFlags { + None = 0, InferUnionTypes = 1, NoDefault = 2, AnyDefault = 4, @@ -2266,6 +2267,7 @@ declare namespace ts { charset?: string; checkJs?: boolean; declaration?: boolean; + emitDeclarationOnly?: boolean; declarationDir?: string; disableSizeLimit?: boolean; downlevelIteration?: boolean; @@ -3976,7 +3978,7 @@ declare namespace ts { } declare namespace ts { type DiagnosticReporter = (diagnostic: Diagnostic) => void; - type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string) => void; + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; interface WatchCompilerHost { /** @@ -3986,7 +3988,7 @@ declare namespace ts { /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string): void; + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; diff --git a/lib/typescript.js b/lib/typescript.js index b4f8d26c1fa..549bb62a2a9 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -575,7 +575,7 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + // empty space NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; // empty space NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; @@ -600,6 +600,7 @@ var ts; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -607,7 +608,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + // hole because there's a hole in node builder flags TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; // hole because there's a hole in node builder flags TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; @@ -632,7 +633,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -648,6 +649,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; // Build symbol name using any nodes needed, instead of just components of an entity name SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -940,6 +943,7 @@ var ts; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; @@ -1511,7 +1515,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -4333,7 +4337,10 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { - var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); @@ -4526,7 +4533,7 @@ var ts; function writeFile(fileName, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } var fd; try { @@ -4724,7 +4731,7 @@ var ts; writeFile: function (path, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } ChakraHost.writeFile(path, data); }, @@ -5497,6 +5504,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -25062,12 +25070,10 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { + function getEmitResolver(sourceFile, cancellationToken) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - if (!ignoreDiagnostics) { - getDiagnostics(sourceFile, cancellationToken); - } + getDiagnostics(sourceFile, cancellationToken); return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -26833,6 +26839,9 @@ var ts; if (flags & 1 /* WriteTypeParametersOrArguments */) { nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -26876,7 +26885,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { - return flags & 9469295 /* NodeBuilderFlagsMask */; + return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -27521,7 +27530,13 @@ var ts; function createEntityNameFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); identifier.symbol = symbol; return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; @@ -27533,7 +27548,13 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } var firstChar = symbolName.charCodeAt(0); var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); if (index === 0 || canUsePropertyAccess) { @@ -27626,6 +27647,9 @@ var ts; function literalTypeToString(type) { return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } + function isDefaultBindingContext(location) { + return location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location); + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -27634,7 +27658,13 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { - if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { return "default"; } if (symbol.declarations && symbol.declarations.length) { @@ -31892,7 +31922,7 @@ var ts; if (ts.isValidESSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); var links = getSymbolLinks(symbol); - return links.type || (links.type = createUniqueESSymbolType(symbol)); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); } return esSymbolType; } @@ -37157,50 +37187,33 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } function getContextualTypeForJsxExpression(node) { - // JSX expression can appear in two position : JSX Element's children or JSX attribute - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - ts.isJsxElement(node.parent) ? - node.parent.openingElement.attributes : - undefined; // node.parent is JsxFragment with no attributes - if (!jsxAttributes) { - return undefined; // don't check children of a fragment - } - // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type - // which is a type of the parameter of the signature we are trying out. - // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - // JSX expression is in JSX attribute - return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); - } - else if (node.parent.kind === 250 /* JsxElement */) { - // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - // JSX expression is in JSX spread attribute - return attributesType; - } + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; } function getContextualTypeForJsxAttribute(attribute) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(attribute.parent); if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return attributesType; + return getContextualType(attribute.parent); } } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily @@ -37311,7 +37324,7 @@ var ts; return getContextualTypeForJsxAttribute(parent); case 252 /* JsxOpeningElement */: case 251 /* JsxSelfClosingElement */: - return getAttributesTypeFromJsxOpeningLikeElement(parent); + return getContextualJsxElementAttributesType(parent); } return undefined; } @@ -37319,6 +37332,124 @@ var ts; node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); return node ? node.contextualMapper : identityMapper; } + function getContextualJsxElementAttributesType(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + var valueType = checkExpression(node.tagName); + if (isTypeAny(valueType)) { + // Short-circuit if the class tag is using an element type 'any' + return anyType; + } + var isJs = ts.isInJavaScriptFile(node); + return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + } + function getJsxSignaturesParameterTypes(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false); + } + function getJsxSignaturesParameterTypesJs(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true); + } + function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type + if (valueType.flags & 2 /* String */) { + return anyType; + } + else if (valueType.flags & 32 /* StringLiteral */) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = valueType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + } + return anyType; + } + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(valueType, 1 /* Construct */); + var ctor = true; + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(valueType, 0 /* Call */); + ctor = false; + if (signatures.length === 0) { + // We found no signatures at all, which is an error + return unknownType; + } + } + return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */); + } + function getJsxPropsTypeFromCallSignature(sig) { + var propsType = getTypeOfFirstParameterOfSignature(sig); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeFromClassType(hostClassType, isJs) { + if (isTypeAny(hostClassType)) { + return hostClassType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + // There is no type ElementAttributesProperty, return 'any' + return anyType; + } + else if (propsName === "") { + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + return hostClassType; + } + else { + var attributesType = getTypeOfPropertyOfType(hostClassType, propsName); + if (!attributesType) { + // There is no property named 'props' on this instance type + return emptyObjectType; + } + else if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getJsxPropsTypeFromConstructSignatureJs(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true); + } + function getJsxPropsTypeFromConstructSignature(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false); + } + function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + var hostClassType = getReturnTypeOfSignature(sig); + if (hostClassType) { + return getJsxPropsTypeFromClassType(hostClassType, isJs); + } + return getJsxPropsTypeFromCallSignature(sig); + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { @@ -37797,7 +37928,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37889,7 +38020,7 @@ var ts; } } else { - childrenTypes.push(checkExpression(child, checkMode)); + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); } } return childrenTypes; @@ -37952,7 +38083,7 @@ var ts; * element is not a class element, or the class element type cannot be determined, returns 'undefined'. * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ - function getJsxElementInstanceType(node, valueType, sourceAttributesType) { + function getJsxElementInstanceType(node, valueType) { ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' @@ -37969,27 +38100,21 @@ var ts; return unknownType; } } - if (sourceAttributesType) { - // Instantiate in context of source type - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); - } + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -38034,7 +38159,7 @@ var ts; } return _jsxElementPropertiesName; } - function getJsxElementChildrenPropertyname() { + function getJsxElementChildrenPropertyName() { if (!_hasComputedJsxElementChildrenPropertyName) { _hasComputedJsxElementChildrenPropertyName = true; _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); @@ -38164,11 +38289,11 @@ var ts; * anyType if there is no type ElementAttributesProperty or there is an error * emptyObjectType if there is no "prop" in the element instance type */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); }), 2 /* Subtype */); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type @@ -38197,7 +38322,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -38207,53 +38332,10 @@ var ts; return statelessAttributesType; } // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType && sourceAttributesType) { + if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - // There is no type ElementAttributesProperty, return 'any' - return anyType; - } - else if (propsName === "") { - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - // There is no property named 'props' on this instance type - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - // Props is of type 'any' or unknown - return attributesType; - } - else { - // Normal case -- add in IntrinsicClassElements and IntrinsicElements - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -38283,20 +38365,8 @@ var ts; * @param node a custom JSX opening-like element * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component */ - function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { - if (!sourceAttributesType) { - // This ensures we cache non-inference uses of this calculation (ie, contextual types or services) - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); - } - return links[linkLocation]; - } - else { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); - } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -38310,7 +38380,7 @@ var ts; else { // Because in language service, the given JSX opening-like element may be incomplete and therefore, // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ true); + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); } } /** @@ -38323,7 +38393,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ false); + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); } } /** @@ -38449,14 +38519,14 @@ var ts; // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. // 3. Check if the two are assignable to each other + // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, /*shouldIncludeAllStatelessAttributesType*/ false); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { @@ -39233,9 +39303,15 @@ var ts; } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, sourceAttributesType, context) { + function inferJsxTypeArguments(signature, node, context) { + // Skip context sensitive pass + var skipContextParamType = getTypeAtPosition(signature, 0); + var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); + inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); + // Standard pass var paramType = getTypeAtPosition(signature, 0); - inferTypes(context.inferences, sourceAttributesType, paramType); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } function inferTypeArguments(node, signature, args, excludeArgument, context) { @@ -39907,7 +39983,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : undefined; while (true) { candidate = originalCandidate; @@ -40463,7 +40539,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -41696,16 +41772,23 @@ var ts; }); return stringType; } + function getContextNode(node) { + if (node.kind === 258 /* JsxAttributes */) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; return result; } function checkExpressionCached(node, checkMode) { @@ -41736,14 +41819,9 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 393216 /* UnionOrIntersection */ && !(contextualType.flags & 8 /* Boolean */)) { - // If the contextual type is a union containing both of the 'true' and 'false' types we - // don't consider it a literal context for boolean literals. - var types_18 = contextualType.types; - return ts.some(types_18, function (t) { - return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_18, trueType) && containsType(types_18, falseType)) && - isLiteralOfContextualType(candidateType, t); - }); + if (contextualType.flags & 393216 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } if (contextualType.flags & 1081344 /* TypeVariable */) { // If the contextual type is a type variable constrained to a primitive type, consider @@ -43592,6 +43670,7 @@ var ts; } break; case 158 /* IndexSignature */: + case 207 /* SemicolonClassElement */: // Can't be private break; default: @@ -46784,7 +46863,7 @@ var ts; // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the // kinds that we do NOT prefix. var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { return undefined; } symbol = exportSymbol; @@ -47314,13 +47393,21 @@ var ts; }); } } + // We do global augmentations seperately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. if (augmentations) { - // merge module augmentations. + // merge _global_ module augmentations. // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { var list = augmentations_1[_d]; for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; mergeModuleAugmentation(augmentation); } } @@ -47347,6 +47434,19 @@ var ts; globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -52333,14 +52433,14 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } var moduleKind = ts.getEmitModuleKind(compilerOptions); - var create = hasExportStarsToExportValues + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) && moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext; @@ -53676,6 +53776,34 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + function getNamedImportCount(node) { + if (!(node.importClause && node.importClause.namedBindings)) + return 0; + var names = node.importClause.namedBindings; + if (!names) + return 0; + if (!ts.isNamedImports(names)) + return 0; + return names.elements.length; + } + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + } + function getImportNeedsImportStarHelper(node) { + return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { var externalImports = []; var exportSpecifiers = ts.createMultiMap(); @@ -53685,6 +53813,7 @@ var ts; var hasExportDefault = false; var exportEquals = undefined; var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { @@ -53694,6 +53823,7 @@ var ts; // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); + hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; case 238 /* ImportEqualsDeclaration */: if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { @@ -53787,7 +53917,7 @@ var ts; break; } } - var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); @@ -57856,7 +57986,7 @@ var ts; if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); } return ts.visitEachChild(node, visitor, context); } @@ -61407,49 +61537,54 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { - ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + if (node.transformFlags & 524288 /* ContainsSpread */ || + node.expression.kind === 97 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 97 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 524288 /* ContainsSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 97 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); } - var resultingCall; - if (node.transformFlags & 524288 /* ContainsSpread */) { - // [source] - // f(...a, b) - // x.m(...a, b) - // super(...a, b) - // super.m(...a, b) // in static - // super.m(...a, b) // in instance - // - // [output] - // f.apply(void 0, a.concat([b])) - // (_a = x).m.apply(_a, a.concat([b])) - // _super.apply(this, a.concat([b])) - // _super.m.apply(this, a.concat([b])) - // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); - } - else { - // [source] - // super(a) - // super.m(a) // in static - // super.m(a) // in instance - // - // [output] - // _super.call(this, a) - // _super.m.call(this, a) - // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), - /*location*/ node); - } - if (node.expression.kind === 97 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); - resultingCall = assignToCapturedThis - ? ts.createAssignment(ts.createIdentifier("_this"), initializer) - : initializer; - } - return ts.setOriginalNode(resultingCall, node); + return ts.visitEachChild(node, visitor, context); } /** * Visits a NewExpression that contains a spread element. @@ -65225,11 +65360,11 @@ var ts; if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { return innerExpr; } - if (ts.getNamespaceDeclarationNode(node)) { + if (ts.getImportNeedsImportStarHelper(node)) { context.requestEmitHelper(importStarHelper); return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); } - if (ts.isDefaultImport(node)) { + if (ts.getImportNeedsImportDefaultHelper(node)) { context.requestEmitHelper(importDefaultHelper); return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); } @@ -68918,7 +69053,7 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); @@ -68934,7 +69069,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -69172,7 +69307,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; @@ -70557,7 +70692,7 @@ var ts; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; // Make sure not to write js file and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { if (!emitOnlyDtsFiles) { printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); } @@ -74368,7 +74503,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -75255,6 +75390,14 @@ var ts; if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } + if (options.emitDeclarationOnly) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); @@ -75275,7 +75418,9 @@ var ts; var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); } @@ -76993,8 +77138,11 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { - if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && + !options.extendedDiagnostics && + !options.diagnostics) { system.clearScreen(); } } @@ -77003,14 +77151,14 @@ var ts; */ function createWatchStatusReporter(system, pretty) { return pretty ? - function (diagnostic, newLine) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic); + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); system.write(output); } : - function (diagnostic, newLine) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic); + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = new Date().toLocaleTimeString() + " - "; output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); system.write(output); @@ -77455,7 +77603,7 @@ var ts; } function reportWatchDiagnostic(message) { if (host.onWatchStatusChange) { - host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions); } } // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch @@ -77812,6 +77960,12 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, { name: "sourceMap", type: "boolean", @@ -78946,9 +79100,9 @@ var ts; return x === undefined || x === null; } function directoryOfCombinedPath(fileName, basePath) { - // Use the `identity` function to avoid canonicalizing the path, as it must remain noncanonical + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical // until consistient casing errors are reported - return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } /** * Parse the contents of a config file from json or json source file (tsconfig.json). @@ -78965,8 +79119,7 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; @@ -79052,20 +79205,20 @@ var ts; * This *just* extracts options/include/exclude/files out of a config file. * It does *not* resolve the included files. */ - function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); return { raw: json || convertToObject(sourceFile, errors) }; } var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; @@ -79087,7 +79240,7 @@ var ts; } return ownConfig; } - function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } @@ -79103,12 +79256,12 @@ var ts; } else { var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { var options = getDefaultCompilerOptions(configFileName); var typeAcquisition, typingOptionstypeAcquisition; var extendedConfigPath; @@ -79126,7 +79279,7 @@ var ts; switch (key) { case "extends": var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -79160,14 +79313,14 @@ var ts; } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { @@ -79177,7 +79330,7 @@ var ts; } return extendedConfigPath; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -79187,13 +79340,13 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; var mapPropertiesInRawIfNotUndefined = function (propertyName) { if (raw_2[propertyName]) { @@ -81103,7 +81256,7 @@ var ts; ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; @@ -82230,15 +82383,15 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (pathCompletion) { + var _loop_7 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === pathCompletion; })) { - result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(createCompletionEntryForModule(name, kind, span)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var pathCompletion = _a[_i]; - _loop_7(pathCompletion); + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_7(name, kind); } } } @@ -82252,8 +82405,8 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { - var moduleName = _c[_b]; + for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { + var moduleName = _d[_c]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; @@ -82261,11 +82414,11 @@ var ts; function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" /* directory */ }] : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); if (!ts.startsWith(fragment, pathPrefix)) { - return ts.emptyArray; + return [{ name: pathPrefix, kind: "directory" /* directory */ }]; } var remainingFragment = fragment.slice(pathPrefix.length); return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); @@ -82294,19 +82447,22 @@ var ts; // that encodes the suffix, but we would have to escape the character "?" which readDirectory // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - var directories = tryGetDirectories(host, baseDirectory); + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); }); + var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); }); // Trim away prefix and suffix - return ts.mapDefined(ts.concatenate(matches, directories), function (match) { - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - return; - } - var start = completePrefix.length; - var length = normalizedMatch.length - start - normalizedSuffix.length; - return ts.removeFileExtension(normalizedMatch.substr(start, length)); + return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { + var name = _a.name, kind = _a.kind; + var normalizedMatch = ts.normalizePath(name); + var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); + return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; }); } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); @@ -82503,7 +82659,13 @@ var ts; return false; } function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); + if (path === "./" || path === ".\\") { + // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. + // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. + return ""; + } + var norm = ts.normalizePath(path); + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used @@ -82520,10 +82682,10 @@ var ts; var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* previousToken.end); + // If `contextToken !== previousToken`, this is `class C ex/**/`. + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; @@ -85126,6 +85306,11 @@ var ts; if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name); } + else if (ts.isDefaultImport(direct)) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); + addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + directImports.push(direct); + } else { directImports.push(direct); } @@ -90348,6 +90533,7 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; @@ -90370,9 +90556,8 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); @@ -90420,7 +90605,7 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index c7c9d5c3d0a..2f169942c29 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1799,7 +1799,6 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, - WriteDefaultSymbolWithoutName = 4, UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, @@ -1821,12 +1820,12 @@ declare namespace ts { IgnoreErrors = 3112960, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, + InInitialEntityName = 16777216, } enum TypeFormatFlags { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, - WriteDefaultSymbolWithoutName = 4, UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, @@ -1844,13 +1843,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469295, + NodeBuilderFlagsMask = 9469291, } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, + UseAliasDefinedOutsideCurrentScope = 8, } /** * @deprecated @@ -2192,6 +2192,7 @@ declare namespace ts { isFixed: boolean; } enum InferenceFlags { + None = 0, InferUnionTypes = 1, NoDefault = 2, AnyDefault = 4, @@ -2266,6 +2267,7 @@ declare namespace ts { charset?: string; checkJs?: boolean; declaration?: boolean; + emitDeclarationOnly?: boolean; declarationDir?: string; disableSizeLimit?: boolean; downlevelIteration?: boolean; @@ -3976,7 +3978,7 @@ declare namespace ts { } declare namespace ts { type DiagnosticReporter = (diagnostic: Diagnostic) => void; - type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string) => void; + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; interface WatchCompilerHost { /** @@ -3986,7 +3988,7 @@ declare namespace ts { /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string): void; + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index b4f8d26c1fa..549bb62a2a9 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -575,7 +575,7 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + // empty space NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; // empty space NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; @@ -600,6 +600,7 @@ var ts; // State NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -607,7 +608,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + // hole because there's a hole in node builder flags TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; // hole because there's a hole in node builder flags TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; @@ -632,7 +633,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -648,6 +649,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; // Build symbol name using any nodes needed, instead of just components of an entity name SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; + // Prefer aliases which are not directly visible + SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -940,6 +943,7 @@ var ts; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { + InferenceFlags[InferenceFlags["None"] = 0] = "None"; InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; @@ -1511,7 +1515,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -4333,7 +4337,10 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { - var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; + // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual + // byte order mark from the specified encoding. Using any other byte order mark does + // not actually work. + var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); @@ -4526,7 +4533,7 @@ var ts; function writeFile(fileName, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } var fd; try { @@ -4724,7 +4731,7 @@ var ts; writeFile: function (path, data, writeByteOrderMark) { // If a BOM is required, emit one if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } ChakraHost.writeFile(path, data); }, @@ -5497,6 +5504,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -25062,12 +25070,10 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { + function getEmitResolver(sourceFile, cancellationToken) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - if (!ignoreDiagnostics) { - getDiagnostics(sourceFile, cancellationToken); - } + getDiagnostics(sourceFile, cancellationToken); return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -26833,6 +26839,9 @@ var ts; if (flags & 1 /* WriteTypeParametersOrArguments */) { nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; } + if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { + nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -26876,7 +26885,7 @@ var ts; return result; } function toNodeBuilderFlags(flags) { - return flags & 9469295 /* NodeBuilderFlagsMask */; + return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -27521,7 +27530,13 @@ var ts; function createEntityNameFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); identifier.symbol = symbol; return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; @@ -27533,7 +27548,13 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } var symbolName = getNameOfSymbolAsWritten(symbol, context); + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } var firstChar = symbolName.charCodeAt(0); var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); if (index === 0 || canUsePropertyAccess) { @@ -27626,6 +27647,9 @@ var ts; function literalTypeToString(type) { return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } + function isDefaultBindingContext(location) { + return location.kind === 269 /* SourceFile */ || ts.isAmbientModule(location); + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -27634,7 +27658,13 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { - if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) && + // If it's not the first part of an entity name, it must print as `default` + (!(context.flags & 16777216 /* InInitialEntityName */) || + // if the symbol is synthesized, it will only be referenced externally it must print as `default` + !symbol.declarations || + // if not in the same binding context (source file, module declaration), it must print as `default` + (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) { return "default"; } if (symbol.declarations && symbol.declarations.length) { @@ -31892,7 +31922,7 @@ var ts; if (ts.isValidESSymbolDeclaration(node)) { var symbol = getSymbolOfNode(node); var links = getSymbolLinks(symbol); - return links.type || (links.type = createUniqueESSymbolType(symbol)); + return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol)); } return esSymbolType; } @@ -37157,50 +37187,33 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } + function getContextualTypeForChildJsxExpression(node) { + var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); + return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + } function getContextualTypeForJsxExpression(node) { - // JSX expression can appear in two position : JSX Element's children or JSX attribute - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - ts.isJsxElement(node.parent) ? - node.parent.openingElement.attributes : - undefined; // node.parent is JsxFragment with no attributes - if (!jsxAttributes) { - return undefined; // don't check children of a fragment - } - // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type - // which is a type of the parameter of the signature we are trying out. - // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - // JSX expression is in JSX attribute - return getTypeOfPropertyOfContextualType(attributesType, node.parent.name.escapedText); - } - else if (node.parent.kind === 250 /* JsxElement */) { - // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - // JSX expression is in JSX spread attribute - return attributesType; - } + var exprParent = node.parent; + return ts.isJsxAttributeLike(exprParent) + ? getContextualType(node) + : ts.isJsxElement(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent) + : undefined; } function getContextualTypeForJsxAttribute(attribute) { // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type // which is a type of the parameter of the signature we are trying out. // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(attribute.parent); if (ts.isJsxAttribute(attribute)) { + var attributesType = getApparentTypeOfContextualType(attribute.parent); if (!attributesType || isTypeAny(attributesType)) { return undefined; } return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText); } else { - return attributesType; + return getContextualType(attribute.parent); } } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily @@ -37311,7 +37324,7 @@ var ts; return getContextualTypeForJsxAttribute(parent); case 252 /* JsxOpeningElement */: case 251 /* JsxSelfClosingElement */: - return getAttributesTypeFromJsxOpeningLikeElement(parent); + return getContextualJsxElementAttributesType(parent); } return undefined; } @@ -37319,6 +37332,124 @@ var ts; node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); return node ? node.contextualMapper : identityMapper; } + function getContextualJsxElementAttributesType(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + var valueType = checkExpression(node.tagName); + if (isTypeAny(valueType)) { + // Short-circuit if the class tag is using an element type 'any' + return anyType; + } + var isJs = ts.isInJavaScriptFile(node); + return mapType(valueType, isJs ? getJsxSignaturesParameterTypesJs : getJsxSignaturesParameterTypes); + } + function getJsxSignaturesParameterTypes(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ false); + } + function getJsxSignaturesParameterTypesJs(valueType) { + return getJsxSignaturesParameterTypesInternal(valueType, /*isJs*/ true); + } + function getJsxSignaturesParameterTypesInternal(valueType, isJs) { + // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type + if (valueType.flags & 2 /* String */) { + return anyType; + } + else if (valueType.flags & 32 /* StringLiteral */) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = valueType.value; + var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + } + return anyType; + } + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(valueType, 1 /* Construct */); + var ctor = true; + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(valueType, 0 /* Call */); + ctor = false; + if (signatures.length === 0) { + // We found no signatures at all, which is an error + return unknownType; + } + } + return getUnionType(ts.map(signatures, ctor ? isJs ? getJsxPropsTypeFromConstructSignatureJs : getJsxPropsTypeFromConstructSignature : getJsxPropsTypeFromCallSignature), 0 /* None */); + } + function getJsxPropsTypeFromCallSignature(sig) { + var propsType = getTypeOfFirstParameterOfSignature(sig); + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + propsType = intersectTypes(intrinsicAttribs, propsType); + } + return propsType; + } + function getJsxPropsTypeFromClassType(hostClassType, isJs) { + if (isTypeAny(hostClassType)) { + return hostClassType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + // There is no type ElementAttributesProperty, return 'any' + return anyType; + } + else if (propsName === "") { + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + return hostClassType; + } + else { + var attributesType = getTypeOfPropertyOfType(hostClassType, propsName); + if (!attributesType) { + // There is no property named 'props' on this instance type + return emptyObjectType; + } + else if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + : intrinsicClassAttribs, apparentAttributesType); + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getJsxPropsTypeFromConstructSignatureJs(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ true); + } + function getJsxPropsTypeFromConstructSignature(sig) { + return getJsxPropsTypeFromConstructSignatureInternal(sig, /*isJs*/ false); + } + function getJsxPropsTypeFromConstructSignatureInternal(sig, isJs) { + var hostClassType = getReturnTypeOfSignature(sig); + if (hostClassType) { + return getJsxPropsTypeFromClassType(hostClassType, isJs); + } + return getJsxPropsTypeFromCallSignature(sig); + } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { @@ -37797,7 +37928,7 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37889,7 +38020,7 @@ var ts; } } else { - childrenTypes.push(checkExpression(child, checkMode)); + childrenTypes.push(checkExpressionForMutableLocation(child, checkMode)); } } return childrenTypes; @@ -37952,7 +38083,7 @@ var ts; * element is not a class element, or the class element type cannot be determined, returns 'undefined'. * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ - function getJsxElementInstanceType(node, valueType, sourceAttributesType) { + function getJsxElementInstanceType(node, valueType) { ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' @@ -37969,27 +38100,21 @@ var ts; return unknownType; } } - if (sourceAttributesType) { - // Instantiate in context of source type - var instantiatedSignatures = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; - if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); - var typeArguments = inferJsxTypeArguments(signature, sourceAttributesType, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - else { - instantiatedSignatures.push(signature); - } + // Instantiate in context of source type + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var isJavascript = ts.isInJavaScriptFile(node); + var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } + else { + instantiatedSignatures.push(signature); } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); - } - else { - // Do not instantiate if no source type is provided - type parameters and their constraints will be used by contextual typing - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */); } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -38034,7 +38159,7 @@ var ts; } return _jsxElementPropertiesName; } - function getJsxElementChildrenPropertyname() { + function getJsxElementChildrenPropertyName() { if (!_hasComputedJsxElementChildrenPropertyName) { _hasComputedJsxElementChildrenPropertyName = true; _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); @@ -38164,11 +38289,11 @@ var ts; * anyType if there is no type ElementAttributesProperty or there is an error * emptyObjectType if there is no "prop" in the element instance type */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, elementType, elementClassType) { + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { if (elementType.flags & 131072 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, sourceAttributesType, type, elementClassType); + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); }), 2 /* Subtype */); } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type @@ -38197,7 +38322,7 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType, sourceAttributesType); + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -38207,53 +38332,10 @@ var ts; return statelessAttributesType; } // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType && sourceAttributesType) { + if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - // There is no type ElementAttributesProperty, return 'any' - return anyType; - } - else if (propsName === "") { - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - // There is no property named 'props' on this instance type - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - // Props is of type 'any' or unknown - return attributesType; - } - else { - // Normal case -- add in IntrinsicClassElements and IntrinsicElements - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } + return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement)); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -38283,20 +38365,8 @@ var ts; * @param node a custom JSX opening-like element * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component */ - function getCustomJsxElementAttributesType(node, sourceAttributesType, shouldIncludeAllStatelessAttributesType) { - if (!sourceAttributesType) { - // This ensures we cache non-inference uses of this calculation (ie, contextual types or services) - var links = getNodeLinks(node); - var linkLocation = shouldIncludeAllStatelessAttributesType ? "resolvedJsxElementAllAttributesType" : "resolvedJsxElementAttributesType"; - if (!links[linkLocation]) { - var elemClassType = getJsxGlobalElementClassType(); - return links[linkLocation] = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), elemClassType); - } - return links[linkLocation]; - } - else { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, sourceAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); - } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxGlobalElementClassType()); } /** * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. @@ -38310,7 +38380,7 @@ var ts; else { // Because in language service, the given JSX opening-like element may be incomplete and therefore, // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ true); + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); } } /** @@ -38323,7 +38393,7 @@ var ts; return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } else { - return getCustomJsxElementAttributesType(node, /*sourceAttributesType*/ undefined, /*shouldIncludeAllStatelessAttributesType*/ false); + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); } } /** @@ -38449,14 +38519,14 @@ var ts; // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. // 3. Check if the two are assignable to each other + // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, sourceAttributesType, /*shouldIncludeAllStatelessAttributesType*/ false); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { @@ -39233,9 +39303,15 @@ var ts; } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature, sourceAttributesType, context) { + function inferJsxTypeArguments(signature, node, context) { + // Skip context sensitive pass + var skipContextParamType = getTypeAtPosition(signature, 0); + var checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); + inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); + // Standard pass var paramType = getTypeAtPosition(signature, 0); - inferTypes(context.inferences, sourceAttributesType, paramType); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } function inferTypeArguments(node, signature, args, excludeArgument, context) { @@ -39907,7 +39983,7 @@ var ts; } var candidate = void 0; var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : undefined; while (true) { candidate = originalCandidate; @@ -40463,7 +40539,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -41696,16 +41772,23 @@ var ts; }); return stringType; } + function getContextNode(node) { + if (node.kind === 258 /* JsxAttributes */) { + return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) + } + return node; + } function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; + var context = getContextNode(node); + var saveContextualType = context.contextualType; + var saveContextualMapper = context.contextualMapper; + context.contextualType = contextualType; + context.contextualMapper = contextualMapper; var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; + context.contextualType = saveContextualType; + context.contextualMapper = saveContextualMapper; return result; } function checkExpressionCached(node, checkMode) { @@ -41736,14 +41819,9 @@ var ts; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 393216 /* UnionOrIntersection */ && !(contextualType.flags & 8 /* Boolean */)) { - // If the contextual type is a union containing both of the 'true' and 'false' types we - // don't consider it a literal context for boolean literals. - var types_18 = contextualType.types; - return ts.some(types_18, function (t) { - return !(t.flags & 128 /* BooleanLiteral */ && containsType(types_18, trueType) && containsType(types_18, falseType)) && - isLiteralOfContextualType(candidateType, t); - }); + if (contextualType.flags & 393216 /* UnionOrIntersection */) { + var types = contextualType.types; + return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } if (contextualType.flags & 1081344 /* TypeVariable */) { // If the contextual type is a type variable constrained to a primitive type, consider @@ -43592,6 +43670,7 @@ var ts; } break; case 158 /* IndexSignature */: + case 207 /* SemicolonClassElement */: // Can't be private break; default: @@ -46784,7 +46863,7 @@ var ts; // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the // kinds that we do NOT prefix. var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) { return undefined; } symbol = exportSymbol; @@ -47314,13 +47393,21 @@ var ts; }); } } + // We do global augmentations seperately from module augmentations (and before creating global types) because they + // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, + // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require + // checking for an export or property on the module (if export=) which, in turn, can fall back to the + // apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we + // did module augmentations prior to finalizing the global types. if (augmentations) { - // merge module augmentations. + // merge _global_ module augmentations. // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { var list = augmentations_1[_d]; for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { var augmentation = list_1[_e]; + if (!ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; mergeModuleAugmentation(augmentation); } } @@ -47347,6 +47434,19 @@ var ts; globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + if (augmentations) { + // merge _nonglobal_ module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _f = 0, augmentations_2 = augmentations; _f < augmentations_2.length; _f++) { + var list = augmentations_2[_f]; + for (var _g = 0, list_2 = list; _g < list_2.length; _g++) { + var augmentation = list_2[_g]; + if (ts.isGlobalScopeAugmentation(augmentation.parent)) + continue; + mergeModuleAugmentation(augmentation); + } + } + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -52333,14 +52433,14 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } var moduleKind = ts.getEmitModuleKind(compilerOptions); - var create = hasExportStarsToExportValues + var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault)) && moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext; @@ -53676,6 +53776,34 @@ var ts; return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; + function getNamedImportCount(node) { + if (!(node.importClause && node.importClause.namedBindings)) + return 0; + var names = node.importClause.namedBindings; + if (!names) + return 0; + if (!ts.isNamedImports(names)) + return 0; + return names.elements.length; + } + function containsDefaultReference(node) { + if (!node) + return false; + if (!ts.isNamedImports(node)) + return false; + return ts.some(node.elements, isNamedDefaultReference); + } + function isNamedDefaultReference(e) { + return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + } + function getImportNeedsImportStarHelper(node) { + return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; + function getImportNeedsImportDefaultHelper(node) { + return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + } + ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { var externalImports = []; var exportSpecifiers = ts.createMultiMap(); @@ -53685,6 +53813,7 @@ var ts; var hasExportDefault = false; var exportEquals = undefined; var hasExportStarsToExportValues = false; + var hasImportStarOrImportDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { @@ -53694,6 +53823,7 @@ var ts; // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); + hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; case 238 /* ImportEqualsDeclaration */: if (node.moduleReference.kind === 249 /* ExternalModuleReference */) { @@ -53787,7 +53917,7 @@ var ts; break; } } - var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); @@ -57856,7 +57986,7 @@ var ts; if (statement.kind === 217 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); } return ts.visitEachChild(node, visitor, context); } @@ -61407,49 +61537,54 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; - if (node.expression.kind === 97 /* SuperKeyword */) { - ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + if (node.transformFlags & 524288 /* ContainsSpread */ || + node.expression.kind === 97 /* SuperKeyword */ || + ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { + var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 97 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); + } + var resultingCall = void 0; + if (node.transformFlags & 524288 /* ContainsSpread */) { + // [source] + // f(...a, b) + // x.m(...a, b) + // super(...a, b) + // super.m(...a, b) // in static + // super.m(...a, b) // in instance + // + // [output] + // f.apply(void 0, a.concat([b])) + // (_a = x).m.apply(_a, a.concat([b])) + // _super.apply(this, a.concat([b])) + // _super.m.apply(this, a.concat([b])) + // _super.prototype.m.apply(this, a.concat([b])) + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + } + else { + // [source] + // super(a) + // super.m(a) // in static + // super.m(a) // in instance + // + // [output] + // _super.call(this, a) + // _super.m.call(this, a) + // _super.prototype.m.call(this, a) + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + /*location*/ node); + } + if (node.expression.kind === 97 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + resultingCall = assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return ts.setOriginalNode(resultingCall, node); } - var resultingCall; - if (node.transformFlags & 524288 /* ContainsSpread */) { - // [source] - // f(...a, b) - // x.m(...a, b) - // super(...a, b) - // super.m(...a, b) // in static - // super.m(...a, b) // in instance - // - // [output] - // f.apply(void 0, a.concat([b])) - // (_a = x).m.apply(_a, a.concat([b])) - // _super.apply(this, a.concat([b])) - // _super.m.apply(this, a.concat([b])) - // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); - } - else { - // [source] - // super(a) - // super.m(a) // in static - // super.m(a) // in instance - // - // [output] - // _super.call(this, a) - // _super.m.call(this, a) - // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), - /*location*/ node); - } - if (node.expression.kind === 97 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); - resultingCall = assignToCapturedThis - ? ts.createAssignment(ts.createIdentifier("_this"), initializer) - : initializer; - } - return ts.setOriginalNode(resultingCall, node); + return ts.visitEachChild(node, visitor, context); } /** * Visits a NewExpression that contains a spread element. @@ -65225,11 +65360,11 @@ var ts; if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { return innerExpr; } - if (ts.getNamespaceDeclarationNode(node)) { + if (ts.getImportNeedsImportStarHelper(node)) { context.requestEmitHelper(importStarHelper); return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); } - if (ts.isDefaultImport(node)) { + if (ts.getImportNeedsImportDefaultHelper(node)) { context.requestEmitHelper(importDefaultHelper); return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); } @@ -68918,7 +69053,7 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); @@ -68934,7 +69069,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -69172,7 +69307,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; @@ -70557,7 +70692,7 @@ var ts; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; // Make sure not to write js file and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { if (!emitOnlyDtsFiles) { printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); } @@ -74368,7 +74503,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -75255,6 +75390,14 @@ var ts; if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } + if (options.emitDeclarationOnly) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declarations"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); @@ -75275,7 +75418,9 @@ var ts; var emitHost = getEmitHost(); var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); }); } @@ -76993,8 +77138,11 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { - if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { + if (system.clearScreen && + diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && + !options.extendedDiagnostics && + !options.diagnostics) { system.clearScreen(); } } @@ -77003,14 +77151,14 @@ var ts; */ function createWatchStatusReporter(system, pretty) { return pretty ? - function (diagnostic, newLine) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic); + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); system.write(output); } : - function (diagnostic, newLine) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic); + function (diagnostic, newLine, options) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = new Date().toLocaleTimeString() + " - "; output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); system.write(output); @@ -77455,7 +77603,7 @@ var ts; } function reportWatchDiagnostic(message) { if (host.onWatchStatusChange) { - host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions); } } // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch @@ -77812,6 +77960,12 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, { name: "sourceMap", type: "boolean", @@ -78946,9 +79100,9 @@ var ts; return x === undefined || x === null; } function directoryOfCombinedPath(fileName, basePath) { - // Use the `identity` function to avoid canonicalizing the path, as it must remain noncanonical + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical // until consistient casing errors are reported - return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } /** * Parse the contents of a config file from json or json source file (tsconfig.json). @@ -78965,8 +79119,7 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; @@ -79052,20 +79205,20 @@ var ts; * This *just* extracts options/include/exclude/files out of a config file. * It does *not* resolve the included files. */ - function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); return { raw: json || convertToObject(sourceFile, errors) }; } var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); if (ownConfig.extendedConfigPath) { // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; @@ -79087,7 +79240,7 @@ var ts; } return ownConfig; } - function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } @@ -79103,12 +79256,12 @@ var ts; } else { var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { var options = getDefaultCompilerOptions(configFileName); var typeAcquisition, typingOptionstypeAcquisition; var extendedConfigPath; @@ -79126,7 +79279,7 @@ var ts; switch (key) { case "extends": var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -79160,14 +79313,14 @@ var ts; } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { @@ -79177,7 +79330,7 @@ var ts; } return extendedConfigPath; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -79187,13 +79340,13 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; var mapPropertiesInRawIfNotUndefined = function (propertyName) { if (raw_2[propertyName]) { @@ -81103,7 +81256,7 @@ var ts; ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; @@ -82230,15 +82383,15 @@ var ts; for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (pathCompletion) { + var _loop_7 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === pathCompletion; })) { - result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(createCompletionEntryForModule(name, kind, span)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var pathCompletion = _a[_i]; - _loop_7(pathCompletion); + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_7(name, kind); } } } @@ -82252,8 +82405,8 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { - var moduleName = _c[_b]; + for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { + var moduleName = _d[_c]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; @@ -82261,11 +82414,11 @@ var ts; function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" /* directory */ }] : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); if (!ts.startsWith(fragment, pathPrefix)) { - return ts.emptyArray; + return [{ name: pathPrefix, kind: "directory" /* directory */ }]; } var remainingFragment = fragment.slice(pathPrefix.length); return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); @@ -82294,19 +82447,22 @@ var ts; // that encodes the suffix, but we would have to escape the character "?" which readDirectory // doesn't support. For now, this is safer but slower var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - var directories = tryGetDirectories(host, baseDirectory); + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(function (name) { return ({ name: name, kind: "script" /* scriptElement */ }); }); + var directories = tryGetDirectories(host, baseDirectory).map(function (d) { return ts.combinePaths(baseDirectory, d); }).map(function (name) { return ({ name: name, kind: "directory" /* directory */ }); }); // Trim away prefix and suffix - return ts.mapDefined(ts.concatenate(matches, directories), function (match) { - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - return; - } - var start = completePrefix.length; - var length = normalizedMatch.length - start - normalizedSuffix.length; - return ts.removeFileExtension(normalizedMatch.substr(start, length)); + return ts.mapDefined(ts.concatenate(matches, directories), function (_a) { + var name = _a.name, kind = _a.kind; + var normalizedMatch = ts.normalizePath(name); + var inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); + return inner !== undefined ? { name: removeLeadingDirectorySeparator(ts.removeFileExtension(inner)), kind: kind } : undefined; }); } + function withoutStartAndEnd(s, start, end) { + return ts.startsWith(s, start) && ts.endsWith(s, end) ? s.slice(start.length, s.length - end.length) : undefined; + } + function removeLeadingDirectorySeparator(path) { + return path[0] === ts.directorySeparator ? path.slice(1) : path; + } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); @@ -82503,7 +82659,13 @@ var ts; return false; } function normalizeAndPreserveTrailingSlash(path) { - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path); + if (path === "./" || path === ".\\") { + // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. + // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. + return ""; + } + var norm = ts.normalizePath(path); + return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used @@ -82520,10 +82682,10 @@ var ts; var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* previousToken.end); + // If `contextToken !== previousToken`, this is `class C ex/**/`. + && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { return ts.isFunctionLikeKind(kind) && kind !== 153 /* Constructor */; @@ -85126,6 +85306,11 @@ var ts; if (namedBindings && namedBindings.kind === 241 /* NamespaceImport */) { handleNamespaceImport(direct, namedBindings.name); } + else if (ts.isDefaultImport(direct)) { + var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); + addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports + directImports.push(direct); + } else { directImports.push(direct); } @@ -90348,6 +90533,7 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; @@ -90370,9 +90556,8 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); @@ -90420,7 +90605,7 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index e38fc9a3910..71dbf5a26ce 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -142,7 +142,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".1"; + ts.version = ts.versionMajorMinor + ".2"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -2547,7 +2547,7 @@ var ts; } ts.getNodeMajorVersion = getNodeMajorVersion; ts.sys = (function () { - var utf8ByteOrderMark = "\u00EF\u00BB\u00BF"; + var byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { var _fs = require("fs"); var _path = require("path"); @@ -2711,7 +2711,7 @@ var ts; } function writeFile(fileName, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } var fd; try { @@ -2893,7 +2893,7 @@ var ts; }, writeFile: function (path, data, writeByteOrderMark) { if (writeByteOrderMark) { - data = utf8ByteOrderMark + data; + data = byteOrderMarkIndicator + data; } ChakraHost.writeFile(path, data); }, @@ -3658,6 +3658,7 @@ var ts; Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), + Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), @@ -15991,6 +15992,12 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Generates_corresponding_d_ts_file, }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, { name: "sourceMap", type: "boolean", @@ -17031,7 +17038,7 @@ var ts; return x === undefined || x === null; } function directoryOfCombinedPath(fileName, basePath) { - return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } @@ -17039,8 +17046,7 @@ var ts; if (extraFileExtensions === void 0) { extraFileExtensions = []; } ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); var raw = parsedConfig.raw; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; @@ -17120,19 +17126,19 @@ var ts; function isSuccessfulParsedTsconfig(value) { return !!value.options; } - function parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors) { + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); if (resolutionStack.indexOf(resolvedPath) >= 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); return { raw: json || convertToObject(sourceFile, errors) }; } var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); if (ownConfig.extendedConfigPath) { resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { var baseRaw_1 = extendedConfig.raw; var raw_1 = ownConfig.raw; @@ -17153,7 +17159,7 @@ var ts; } return ownConfig; } - function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } @@ -17167,12 +17173,12 @@ var ts; } else { var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { var options = getDefaultCompilerOptions(configFileName); var typeAcquisition, typingOptionstypeAcquisition; var extendedConfigPath; @@ -17190,7 +17196,7 @@ var ts; switch (key) { case "extends": var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -17224,13 +17230,13 @@ var ts; } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { extendedConfig = ts.normalizeSlashes(extendedConfig); if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { @@ -17240,7 +17246,7 @@ var ts; } return extendedConfigPath; } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); @@ -17250,12 +17256,12 @@ var ts; return undefined; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors); + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); if (sourceFile) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; var mapPropertiesInRawIfNotUndefined = function (propertyName) { if (raw_2[propertyName]) {