From f6a50067d36cf44bc15562ff8c414efdd41897c4 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Mon, 24 Jun 2019 14:55:58 +0300 Subject: [PATCH] @typescript-eslint/indent --- .eslintrc | 8 +- .../importDefinitelyTypedTests.ts | 65 ++-- src/compiler/checker.ts | 192 ++++++------ src/compiler/commandLineParser.ts | 4 +- src/compiler/emitter.ts | 1 - src/compiler/factory.ts | 8 +- src/compiler/moduleSpecifiers.ts | 5 +- src/compiler/parser.ts | 17 +- src/compiler/scanner.ts | 277 +++++++++--------- src/compiler/sys.ts | 4 +- src/compiler/transformers/declarations.ts | 10 +- .../transformers/declarations/diagnostics.ts | 8 +- src/compiler/transformers/es2015.ts | 6 +- src/compiler/transformers/es2018.ts | 4 +- src/compiler/transformers/module/module.ts | 24 +- src/compiler/transformers/module/system.ts | 2 +- src/compiler/transformers/ts.ts | 2 +- src/compiler/types.ts | 76 +++-- src/compiler/utilities.ts | 44 +-- src/compiler/visitor.ts | 12 - src/compiler/watch.ts | 7 +- src/harness/typeWriter.ts | 4 +- src/lib/es2019.array.d.ts | 7 +- src/lib/es2019.string.d.ts | 16 +- src/lib/es2020.string.d.ts | 12 +- src/lib/es2020.symbol.wellknown.d.ts | 22 +- src/lib/es5.d.ts | 10 +- src/lib/esnext.intl.d.ts | 2 +- src/server/editorServices.ts | 56 ++-- src/server/protocol.ts | 36 ++- src/server/session.ts | 2 +- src/services/codefixes/convertToEs6Module.ts | 11 +- .../fixClassIncorrectlyImplementsInterface.ts | 6 +- src/services/codefixes/helpers.ts | 3 +- src/services/codefixes/importFixes.ts | 6 +- src/services/codefixes/inferFromUsage.ts | 2 +- src/services/completions.ts | 12 +- src/services/findAllReferences.ts | 17 +- src/services/formatting/formatting.ts | 4 +- src/services/formatting/formattingScanner.ts | 20 +- src/services/formatting/rulesMap.ts | 13 +- src/services/patternMatcher.ts | 6 +- .../convertParamsToDestructuredObject.ts | 4 +- src/services/refactors/extractSymbol.ts | 44 +-- src/services/refactors/extractType.ts | 4 +- src/services/services.ts | 2 +- src/services/shims.ts | 2 +- src/services/stringCompletions.ts | 7 +- src/services/utilities.ts | 5 +- src/testRunner/projectsRunner.ts | 12 +- .../unittests/config/commandLineParsing.ts | 70 ++--- .../config/convertCompilerOptionsFromJson.ts | 20 +- .../config/convertTypeAcquisitionFromJson.ts | 5 +- src/testRunner/unittests/config/showConfig.ts | 50 ++-- .../unittests/config/tsconfigParsing.ts | 2 +- src/testRunner/unittests/jsDocParsing.ts | 74 ++--- src/testRunner/unittests/moduleResolution.ts | 2 +- src/testRunner/unittests/printer.ts | 5 +- .../cancellableLanguageServiceOperations.ts | 18 +- .../unittests/services/colorization.ts | 8 +- .../services/convertToAsyncFunction.ts | 75 ++--- .../unittests/services/extract/functions.ts | 6 +- .../unittests/services/extract/ranges.ts | 190 +++++------- .../unittests/services/languageService.ts | 2 +- .../unittests/services/organizeImports.ts | 20 +- .../unittests/services/preProcessFile.ts | 173 +++++------ .../unittests/services/textChanges.ts | 32 +- .../unittests/services/transpile.ts | 42 +-- src/testRunner/unittests/transform.ts | 124 ++++---- src/testRunner/unittests/tsbuild/helpers.ts | 3 +- src/testRunner/unittests/tsbuild/sample.ts | 2 +- src/testRunner/unittests/tscWatch/emit.ts | 34 +-- .../unittests/tsserver/metadataInResponse.ts | 10 +- src/tsserver/server.ts | 124 ++++---- .../reference/api/tsserverlibrary.d.ts | 28 ++ 75 files changed, 1115 insertions(+), 1127 deletions(-) diff --git a/.eslintrc b/.eslintrc index b6581a2e8f4..f6451e8206b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -24,7 +24,13 @@ "@typescript-eslint/explicit-member-accessibility": "off", "@typescript-eslint/import/order": "off", "indent": "off", - "@typescript-eslint/indent": "off", + "@typescript-eslint/indent": ["error", 4, { + "flatTernaryExpressions": true, + "FunctionDeclaration": { "parameters": 1, "body": 1 }, + "CallExpression": { "arguments": 1 }, + "ignoredNodes": ["TSTypeAnnotation"], + "SwitchCase": 1 + }], "@typescript-eslint/interface-name-prefix": "error", "@typescript-eslint/member-ordering": "off", "@typescript-eslint/no-angle-bracket-type-assertion": "off", diff --git a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts index 88712d69801..8dbc6a5c668 100644 --- a/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts +++ b/scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts @@ -63,42 +63,41 @@ function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCas maxBuffer: 1 * 1024 * 1024, cwd: testDirectoryPath }, (error, stdout, stderr) => { + console.log("importing " + testCaseName + " ..."); + console.log(cmd); + + if (error) { console.log("importing " + testCaseName + " ..."); console.log(cmd); - - if (error) { - console.log("importing " + testCaseName + " ..."); - console.log(cmd); - console.log("==> error " + JSON.stringify(error)); - console.log("==> stdout " + String(stdout)); - console.log("==> stderr " + String(stderr)); - console.log("\r\n"); - return; - } - - // copy generated file to output location - const outputFilePath = path.join(testDirectoryPath, "iocapture0.json"); - const testCasePath = path.join(rwcTestPath, "DefinitelyTyped_" + testCaseName + ".json"); - copyFileSync(outputFilePath, testCasePath); - - //console.log("output generated at: " + outputFilePath); - - if (!fs.existsSync(testCasePath)) { - throw new Error("could not find test case at: " + testCasePath); - } - else { - fs.unlinkSync(outputFilePath); - fs.rmdirSync(testDirectoryPath); - //console.log("testcase generated at: " + testCasePath); - //console.log("Done."); - } - //console.log("\r\n"); - - }) - .on("error", (error: any) => { console.log("==> error " + JSON.stringify(error)); + console.log("==> stdout " + String(stdout)); + console.log("==> stderr " + String(stderr)); console.log("\r\n"); - }); + return; + } + + // copy generated file to output location + const outputFilePath = path.join(testDirectoryPath, "iocapture0.json"); + const testCasePath = path.join(rwcTestPath, "DefinitelyTyped_" + testCaseName + ".json"); + copyFileSync(outputFilePath, testCasePath); + + //console.log("output generated at: " + outputFilePath); + + if (!fs.existsSync(testCasePath)) { + throw new Error("could not find test case at: " + testCasePath); + } + else { + fs.unlinkSync(outputFilePath); + fs.rmdirSync(testDirectoryPath); + //console.log("testcase generated at: " + testCasePath); + //console.log("Done."); + } + //console.log("\r\n"); + + }).on("error", (error: any) => { + console.log("==> error " + JSON.stringify(error)); + console.log("\r\n"); + }); } function importDefinitelyTypedTests(tscPath: string, rwcTestPath: string, definitelyTypedRoot: string): void { @@ -147,7 +146,7 @@ function importDefinitelyTypedTests(tscPath: string, rwcTestPath: string, defini } } else { - importDefinitelyTypedTest(tscPath, rwcTestPath, d, tsFiles, paramFile); + importDefinitelyTypedTest(tscPath, rwcTestPath, d, tsFiles, paramFile); } } else { diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 123a185dced..d0a5da73937 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -925,8 +925,7 @@ namespace ts { } if (source.exports) { if (!target.exports) target.exports = createSymbolTable(); - mergeSymbolTable(target.exports, source.exports, unidirectional - ); + mergeSymbolTable(target.exports, source.exports, unidirectional); } if (!unidirectional) { recordMergedSymbol(target, source); @@ -4019,7 +4018,8 @@ namespace ts { propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { // Copy comments to node for declaration emit setCommentRange(propertySignature, propertySymbol.valueDeclaration); @@ -4171,13 +4171,12 @@ namespace ts { const modifiers = !(context.flags & NodeBuilderFlags.OmitParameterModifiers) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(getSynthesizedClone) : undefined; const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & CheckFlags.RestParameter; const dotDotDotToken = isRest ? createToken(SyntaxKind.DotDotDotToken) : undefined; - const name = parameterDeclaration - ? parameterDeclaration.name ? - parameterDeclaration.name.kind === SyntaxKind.Identifier ? setEmitFlags(getSynthesizedClone(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : - parameterDeclaration.name.kind === SyntaxKind.QualifiedName ? setEmitFlags(getSynthesizedClone(parameterDeclaration.name.right), EmitFlags.NoAsciiEscaping) : - cloneBindingName(parameterDeclaration.name) : - symbolName(parameterSymbol) - : symbolName(parameterSymbol); + const name = parameterDeclaration ? parameterDeclaration.name ? + parameterDeclaration.name.kind === SyntaxKind.Identifier ? setEmitFlags(getSynthesizedClone(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : + parameterDeclaration.name.kind === SyntaxKind.QualifiedName ? setEmitFlags(getSynthesizedClone(parameterDeclaration.name.right), EmitFlags.NoAsciiEscaping) : + cloneBindingName(parameterDeclaration.name) : + symbolName(parameterSymbol) : + symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & CheckFlags.OptionalParameter; const questionToken = isOptional ? createToken(SyntaxKind.QuestionToken) : undefined; const parameterNode = createParameter( @@ -4443,7 +4442,7 @@ namespace ts { const symbol = chain[index]; if (index === 0) { - context.flags |= NodeBuilderFlags.InInitialEntityName; + context.flags |= NodeBuilderFlags.InInitialEntityName; } const symbolName = getNameOfSymbolAsWritten(symbol, context); context.approximateLength += symbolName.length + 1; @@ -4920,7 +4919,7 @@ namespace ts { } function getDeclarationContainer(node: Node): Node { - return findAncestor(getRootDeclaration(node), node => { + return findAncestor(getRootDeclaration(node), node => { switch (node.kind) { case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarationList: @@ -5286,7 +5285,7 @@ namespace ts { for (const declaration of symbol.declarations) { const expression = (isBinaryExpression(declaration) || isCallExpression(declaration)) ? declaration : isPropertyAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; + undefined; if (!expression) { return errorType; } @@ -7872,7 +7871,7 @@ namespace ts { } return t.flags & TypeFlags.Union && baseTypes.length === types.length ? getUnionType(baseTypes) : t.flags & TypeFlags.Intersection && baseTypes.length ? getIntersectionType(baseTypes) : - undefined; + undefined; } if (t.flags & TypeFlags.Index) { return keyofConstraintType; @@ -8911,13 +8910,14 @@ namespace ts { const isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { const missingAugmentsTag = isJs && isExpressionWithTypeArguments(node) && !isJSDocAugmentsTag(node.parent); - const diag = minTypeArgumentCount === typeParameters.length - ? missingAugmentsTag - ? Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag - : Diagnostics.Generic_type_0_requires_1_type_argument_s - : missingAugmentsTag - ? Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag - : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + const diag = minTypeArgumentCount === typeParameters.length ? + missingAugmentsTag ? + Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag : + Diagnostics.Generic_type_0_requires_1_type_argument_s : + missingAugmentsTag ? + Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : + Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; + const typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { @@ -8959,12 +8959,12 @@ namespace ts { const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { error(node, - minTypeArgumentCount === typeParameters.length - ? Diagnostics.Generic_type_0_requires_1_type_argument_s - : Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, - symbolToString(symbol), - minTypeArgumentCount, - typeParameters.length); + minTypeArgumentCount === typeParameters.length ? + Diagnostics.Generic_type_0_requires_1_type_argument_s : + Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, + symbolToString(symbol), + minTypeArgumentCount, + typeParameters.length); return errorType; } return getTypeAliasInstantiation(symbol, typeArguments); @@ -9663,7 +9663,7 @@ namespace ts { if (typeSet.length === 0) { return includes & TypeFlags.Null ? includes & TypeFlags.IncludesNonWideningType ? nullType : nullWideningType : includes & TypeFlags.Undefined ? includes & TypeFlags.IncludesNonWideningType ? undefinedType : undefinedWideningType : - neverType; + neverType; } } return getUnionTypeFromSortedList(typeSet, includes & TypeFlags.NotPrimitiveUnion ? 0 : ObjectFlags.PrimitiveUnion, aliasSymbol, aliasTypeArguments); @@ -10251,13 +10251,10 @@ namespace ts { } function getIndexNodeForAccessExpression(accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | BindingName | SyntheticExpression) { - return accessNode.kind === SyntaxKind.ElementAccessExpression - ? accessNode.argumentExpression - : accessNode.kind === SyntaxKind.IndexedAccessType - ? accessNode.indexType - : accessNode.kind === SyntaxKind.ComputedPropertyName - ? accessNode.expression - : accessNode; + return accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : + accessNode.kind === SyntaxKind.IndexedAccessType ? accessNode.indexType : + accessNode.kind === SyntaxKind.ComputedPropertyName ? accessNode.expression : + accessNode; } function isGenericObjectType(type: Type): boolean { @@ -11641,7 +11638,7 @@ namespace ts { target === globalObjectType ? !!(source.flags & (TypeFlags.Object | TypeFlags.NonPrimitive)) : target === globalFunctionType ? !!(source.flags & TypeFlags.Object) && isFunctionObjectType(source as ObjectType) : hasBaseType(source, getTargetType(target)); - } + } /** * This is *not* a bi-directional relationship. @@ -13201,9 +13198,8 @@ namespace ts { const filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, t => !!isRelatedTo(t, sourceKeys)) : undefined; // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X. - if (hasOptionalUnionKeys - ? !(filteredByApplicability!.flags & TypeFlags.Never) - : isRelatedTo(targetConstraint, sourceKeys)) { + if (hasOptionalUnionKeys ? !(filteredByApplicability!.flags & TypeFlags.Never) : + isRelatedTo(targetConstraint, sourceKeys)) { const indexingType = hasOptionalUnionKeys ? filteredByApplicability! : getTypeParameterFromMappedType(target); const indexedAccessType = getIndexedAccessType(source, indexingType); const templateType = getTemplateTypeFromMappedType(target); @@ -13431,7 +13427,7 @@ namespace ts { // that S and T are contra-variant whereas X and Y are co-variant. function mappedTypeRelatedTo(source: MappedType, target: MappedType, reportErrors: boolean): Ternary { const modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : - getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); + getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { let result: Ternary; const targetConstraint = getConstraintTypeFromMappedType(target); @@ -16377,9 +16373,8 @@ namespace ts { isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.BigIntLiteral)) { return mapType(typeWithPrimitives, t => t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral) : - t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : - t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : - t); + t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : + t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t); } return typeWithPrimitives; } @@ -17105,7 +17100,7 @@ namespace ts { const discriminantType = getUnionType(clauseTypes); const caseType = discriminantType.flags & TypeFlags.Never ? neverType : - replacePrimitivesWithLiterals(filterType(type, t => areTypesComparable(discriminantType, t)), discriminantType); + replacePrimitivesWithLiterals(filterType(type, t => areTypesComparable(discriminantType, t)), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -17270,8 +17265,8 @@ namespace ts { // two types. return isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); } function narrowTypeByTypePredicate(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type { @@ -17593,7 +17588,7 @@ namespace ts { declaration.flags & NodeFlags.Ambient; const initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration as VariableLikeDeclaration) : type) : type === autoType || type === autoArrayType ? undefinedType : - getOptionalType(type); + getOptionalType(type); const flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the @@ -18201,7 +18196,7 @@ namespace ts { func.kind === SyntaxKind.GetAccessor || func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent : - undefined; + undefined; } function getThisTypeArgument(type: Type): Type | undefined { @@ -19844,25 +19839,25 @@ namespace ts { } function getIntrinsicAttributesTypeFromStringLiteralType(type: StringLiteralType, location: Node): Type | undefined { - // 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 - const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); - if (intrinsicElementsType !== errorType) { - const stringLiteralTypeName = type.value; - const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); - if (indexSignatureType) { - return indexSignatureType; - } - return undefined; + // 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 + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); + if (intrinsicElementsType !== errorType) { + const stringLiteralTypeName = type.value; + const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; + const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); + if (indexSignatureType) { + return indexSignatureType; + } + return undefined; + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; } function checkJsxReturnAssignableToAppropriateBound(refKind: JsxReferenceKind, elemInstanceType: Type, openingLikeElement: Node) { @@ -20990,7 +20985,7 @@ namespace ts { getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; const inferenceTargetType = getReturnTypeOfSignature(signature); - // Inferences made from return types have lower priority than all other inferences. + // Inferences made from return types have lower priority than all other inferences. inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, InferencePriority.ReturnType); // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. We need a separate inference pass here because (a) instantiation of @@ -23893,8 +23888,8 @@ namespace ts { resultType = bigintType; } else if (isTypeAssignableToKind(leftType, TypeFlags.StringLike, /*strict*/ true) || isTypeAssignableToKind(rightType, TypeFlags.StringLike, /*strict*/ true)) { - // If one or both operands are of the String primitive type, the result is of the String primitive type. - resultType = stringType; + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; } else if (isTypeAny(leftType) || isTypeAny(rightType)) { // Otherwise, the result is of type Any. @@ -24003,8 +23998,9 @@ namespace ts { function checkForDisallowedESSymbolOperand(operator: SyntaxKind): boolean { const offendingSymbolOperand = maybeTypeOfKind(leftType, TypeFlags.ESSymbolLike) ? left : - maybeTypeOfKind(rightType, TypeFlags.ESSymbolLike) ? right : - undefined; + maybeTypeOfKind(rightType, TypeFlags.ESSymbolLike) ? right : + undefined; + if (offendingSymbolOperand) { error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator)); return false; @@ -24086,7 +24082,7 @@ namespace ts { case SyntaxKind.ExclamationEqualsEqualsToken: case SyntaxKind.ExclamationEqualsToken: return error(errNode, Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); - } + } return undefined; } } @@ -26308,8 +26304,8 @@ namespace ts { node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { error(node.name, - Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, - idText(node.name.kind === SyntaxKind.QualifiedName ? node.name.right : node.name)); + Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, + idText(node.name.kind === SyntaxKind.QualifiedName ? node.name.right : node.name)); } } } @@ -27775,17 +27771,16 @@ namespace ts { function checkLabeledStatement(node: LabeledStatement) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - findAncestor(node.parent, - current => { - if (isFunctionLike(current)) { - return "quit"; - } - if (current.kind === SyntaxKind.LabeledStatement && (current).label.escapedText === node.label.escapedText) { - grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label)); - return true; - } - return false; - }); + findAncestor(node.parent, current => { + if (isFunctionLike(current)) { + return "quit"; + } + if (current.kind === SyntaxKind.LabeledStatement && (current).label.escapedText === node.label.escapedText) { + grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label)); + return true; + } + return false; + }); } // ensure that label is unique @@ -30274,7 +30269,7 @@ namespace ts { let target: Symbol | undefined; let next: Symbol | undefined = symbol; while (next = getSymbolLinks(next).target) { - target = next; + target = next; } return target; } @@ -30469,10 +30464,9 @@ namespace ts { const exportClause = (node).exportClause; return !!exportClause && some(exportClause.elements, isValueAliasDeclaration); case SyntaxKind.ExportAssignment: - return (node).expression - && (node).expression.kind === SyntaxKind.Identifier - ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) - : true; + return (node).expression && (node).expression.kind === SyntaxKind.Identifier ? + isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) : + true; } return false; } @@ -31604,15 +31598,15 @@ namespace ts { if (type.flags & TypeFlags.String || type.flags & TypeFlags.Number) { return grammarErrorOnNode(parameter.name, - Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, - getTextOfNode(parameter.name), - typeToString(type), - typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); + Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, + getTextOfNode(parameter.name), + typeToString(type), + typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } if (type.flags & TypeFlags.Union && allTypesAssignableToKind(type, TypeFlags.StringLiteral, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, - Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -31980,9 +31974,9 @@ namespace ts { } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { return grammarErrorOnNode(accessor.name, - kind === SyntaxKind.GetAccessor ? - Diagnostics.A_get_accessor_cannot_have_parameters : - Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + kind === SyntaxKind.GetAccessor ? + Diagnostics.A_get_accessor_cannot_have_parameters : + Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } else if (kind === SyntaxKind.SetAccessor) { if (accessor.type) { @@ -32466,7 +32460,7 @@ namespace ts { node.kind === SyntaxKind.ExportAssignment || node.kind === SyntaxKind.NamespaceExportDeclaration || hasModifier(node, ModifierFlags.Ambient | ModifierFlags.Export | ModifierFlags.Default)) { - return false; + return false; } return grammarErrorOnFirstToken(node, Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier); diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index c0363788c9e..a1e2723c742 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -2171,12 +2171,12 @@ namespace ts { return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); } - /*@internal*/ + /*@internal*/ export function canJsonReportNoInutFiles(raw: any) { return !hasProperty(raw, "files") && !hasProperty(raw, "references"); } - /*@internal*/ + /*@internal*/ export function updateErrorForNoInputFiles(result: ExpandResult, configFileName: string, configFileSpecs: ConfigFileSpecs, configParseDiagnostics: Diagnostic[], canJsonReportNoInutFiles: boolean) { const existingErrors = configParseDiagnostics.length; if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 258540ec1bb..6fc2c86136f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1150,7 +1150,6 @@ namespace ts { return emitIdentifier(node); // Parse tree nodes - // Names case SyntaxKind.QualifiedName: return emitQualifiedName(node); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 5c626a8ee45..cc2e5aaef4c 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3457,7 +3457,7 @@ namespace ts { export function createMemberAccessForPropertyName(target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression { if (isComputedPropertyName(memberName)) { - return setTextRange(createElementAccess(target, memberName.expression), location); + return setTextRange(createElementAccess(target, memberName.expression), location); } else { const expression = setTextRange( @@ -4494,10 +4494,8 @@ namespace ts { } const leftKind = getLiteralKindOfBinaryPlusOperand((node).left); - const literalKind = isLiteralKind(leftKind) - && leftKind === getLiteralKindOfBinaryPlusOperand((node).right) - ? leftKind - : SyntaxKind.Unknown; + const literalKind = isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand((node).right) ? leftKind : + SyntaxKind.Unknown; (node).cachedLiteralKind = literalKind; return literalKind; diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index bc448698c69..1a90530fe13 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -30,8 +30,9 @@ namespace ts.moduleSpecifiers { function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences { return { relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative, - ending: hasJSOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension - : getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal, + ending: hasJSOrJsonFileExtension(oldImportSpecifier) ? + Ending.JsExtension : + getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal, }; } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 1e1474379d4..92361981462 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -4746,7 +4746,7 @@ namespace ts { function parseArgumentOrArrayLiteralElement(): Expression { return token() === SyntaxKind.DotDotDotToken ? parseSpreadElement() : token() === SyntaxKind.CommaToken ? createNode(SyntaxKind.OmittedExpression) : - parseAssignmentExpressionOrHigher(); + parseAssignmentExpressionOrHigher(); } function parseArgumentExpression(): Expression { @@ -4848,9 +4848,9 @@ namespace ts { const isAsync = hasModifier(node, ModifierFlags.Async) ? SignatureFlags.Await : SignatureFlags.None; node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : - isGenerator ? doInYieldContext(parseOptionalIdentifier) : - isAsync ? doInAwaitContext(parseOptionalIdentifier) : - parseOptionalIdentifier(); + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); fillSignature(SyntaxKind.ColonToken, isGenerator | isAsync, node); node.body = parseFunctionBlock(isGenerator | isAsync); @@ -5964,9 +5964,8 @@ namespace ts { } function tryParseTypeArguments(): NodeArray | undefined { - return token() === SyntaxKind.LessThanToken - ? parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken) - : undefined; + return token() === SyntaxKind.LessThanToken ? + parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken) : undefined; } function isHeritageClause(): boolean { @@ -6312,9 +6311,7 @@ namespace ts { || node.kind === SyntaxKind.ImportEqualsDeclaration && (node).moduleReference.kind === SyntaxKind.ExternalModuleReference || node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ExportAssignment - || node.kind === SyntaxKind.ExportDeclaration - ? node - : undefined; + || node.kind === SyntaxKind.ExportDeclaration ? node : undefined; } function getImportMetaIfNecessary(sourceFile: SourceFile) { diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 854bc6c521b..b2f44a3f4e8 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -314,9 +314,9 @@ namespace ts { let pos = 0; let lineStart = 0; while (pos < text.length) { - const ch = text.charCodeAt(pos); - pos++; - switch (ch) { + const ch = text.charCodeAt(pos); + pos++; + switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos) === CharacterCodes.lineFeed) { pos++; @@ -427,146 +427,146 @@ namespace ts { ch === CharacterCodes.mathematicalSpace || ch === CharacterCodes.ideographicSpace || ch === CharacterCodes.byteOrderMark; - } + } - export function isLineBreak(ch: number): boolean { - // ES5 7.3: - // The ECMAScript line terminator characters are listed in Table 3. - // Table 3: Line Terminator Characters - // Code Unit Value Name Formal Name - // \u000A Line Feed - // \u000D Carriage Return - // \u2028 Line separator - // \u2029 Paragraph separator - // Only the characters in Table 3 are treated as line terminators. Other new line or line - // breaking characters are treated as white space but not as line terminators. + export function isLineBreak(ch: number): boolean { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. - return ch === CharacterCodes.lineFeed || - ch === CharacterCodes.carriageReturn || - ch === CharacterCodes.lineSeparator || - ch === CharacterCodes.paragraphSeparator; - } + return ch === CharacterCodes.lineFeed || + ch === CharacterCodes.carriageReturn || + ch === CharacterCodes.lineSeparator || + ch === CharacterCodes.paragraphSeparator; + } - function isDigit(ch: number): boolean { - return ch >= CharacterCodes._0 && ch <= CharacterCodes._9; - } + function isDigit(ch: number): boolean { + return ch >= CharacterCodes._0 && ch <= CharacterCodes._9; + } - /* @internal */ - export function isOctalDigit(ch: number): boolean { - return ch >= CharacterCodes._0 && ch <= CharacterCodes._7; - } + /* @internal */ + export function isOctalDigit(ch: number): boolean { + return ch >= CharacterCodes._0 && ch <= CharacterCodes._7; + } - export function couldStartTrivia(text: string, pos: number): boolean { - // Keep in sync with skipTrivia - const ch = text.charCodeAt(pos); - switch (ch) { - case CharacterCodes.carriageReturn: - case CharacterCodes.lineFeed: - case CharacterCodes.tab: - case CharacterCodes.verticalTab: - case CharacterCodes.formFeed: - case CharacterCodes.space: - case CharacterCodes.slash: - // starts of normal trivia - // falls through - case CharacterCodes.lessThan: - case CharacterCodes.bar: - case CharacterCodes.equals: - case CharacterCodes.greaterThan: - // Starts of conflict marker trivia - return true; - case CharacterCodes.hash: - // Only if its the beginning can we have #! trivia - return pos === 0; - default: - return ch > CharacterCodes.maxAsciiCharacter; - } - } + export function couldStartTrivia(text: string, pos: number): boolean { + // Keep in sync with skipTrivia + const ch = text.charCodeAt(pos); + switch (ch) { + case CharacterCodes.carriageReturn: + case CharacterCodes.lineFeed: + case CharacterCodes.tab: + case CharacterCodes.verticalTab: + case CharacterCodes.formFeed: + case CharacterCodes.space: + case CharacterCodes.slash: + // starts of normal trivia + // falls through + case CharacterCodes.lessThan: + case CharacterCodes.bar: + case CharacterCodes.equals: + case CharacterCodes.greaterThan: + // Starts of conflict marker trivia + return true; + case CharacterCodes.hash: + // Only if its the beginning can we have #! trivia + return pos === 0; + default: + return ch > CharacterCodes.maxAsciiCharacter; + } + } - /* @internal */ - export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments = false): number { - if (positionIsSynthesized(pos)) { - return pos; - } + /* @internal */ + export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments = false): number { + if (positionIsSynthesized(pos)) { + return pos; + } - // Keep in sync with couldStartTrivia - while (true) { - const ch = text.charCodeAt(pos); - switch (ch) { - case CharacterCodes.carriageReturn: - if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { - pos++; - } - // falls through - case CharacterCodes.lineFeed: - pos++; - if (stopAfterLineBreak) { - return pos; - } - continue; - case CharacterCodes.tab: - case CharacterCodes.verticalTab: - case CharacterCodes.formFeed: - case CharacterCodes.space: - pos++; - continue; - case CharacterCodes.slash: - if (stopAtComments) { - break; - } - if (text.charCodeAt(pos + 1) === CharacterCodes.slash) { - pos += 2; - while (pos < text.length) { - if (isLineBreak(text.charCodeAt(pos))) { - break; - } - pos++; - } - continue; - } - if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) { - pos += 2; - while (pos < text.length) { - if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) { - pos += 2; - break; - } - pos++; - } - continue; - } - break; + // Keep in sync with couldStartTrivia + while (true) { + const ch = text.charCodeAt(pos); + switch (ch) { + case CharacterCodes.carriageReturn: + if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { + pos++; + } + // falls through + case CharacterCodes.lineFeed: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case CharacterCodes.tab: + case CharacterCodes.verticalTab: + case CharacterCodes.formFeed: + case CharacterCodes.space: + pos++; + continue; + case CharacterCodes.slash: + if (stopAtComments) { + break; + } + if (text.charCodeAt(pos + 1) === CharacterCodes.slash) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; - case CharacterCodes.lessThan: - case CharacterCodes.bar: - case CharacterCodes.equals: - case CharacterCodes.greaterThan: - if (isConflictMarkerTrivia(text, pos)) { - pos = scanConflictMarkerTrivia(text, pos); - continue; - } - break; + case CharacterCodes.lessThan: + case CharacterCodes.bar: + case CharacterCodes.equals: + case CharacterCodes.greaterThan: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; - case CharacterCodes.hash: - if (pos === 0 && isShebangTrivia(text, pos)) { - pos = scanShebangTrivia(text, pos); - continue; - } - break; + case CharacterCodes.hash: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; - default: - if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpaceLike(ch))) { - pos++; - continue; - } - break; - } - return pos; - } - } + default: + if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpaceLike(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } - // All conflict markers consist of the same character repeated seven times. If it is - // a <<<<<<< or >>>>>>> marker then it is also followed by a space. + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followed by a space. const mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text: string, pos: number) { @@ -836,12 +836,13 @@ namespace ts { // Creates a scanner over a (possibly unspecified) range of a piece of text. export function createScanner(languageVersion: ScriptTarget, - skipTrivia: boolean, - languageVariant = LanguageVariant.Standard, - textInitial?: string, - onError?: ErrorCallback, - start?: number, - length?: number): Scanner { + skipTrivia: boolean, + languageVariant = LanguageVariant.Standard, + textInitial?: string, + onError?: ErrorCallback, + start?: number, + length?: number): Scanner { + let text = textInitial!; // Current position (end position of text of current token) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 2f342509719..e3b05087f3c 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -649,10 +649,10 @@ namespace ts { // crypto can be absent on reduced node installations let _crypto: typeof import("crypto") | undefined; try { - _crypto = require("crypto"); + _crypto = require("crypto"); } catch { - _crypto = undefined; + _crypto = undefined; } const Buffer: { diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 4f68c36d919..8a41ddb7651 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -625,10 +625,10 @@ namespace ts { // Namespace import (optionally with visible default) const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; return visibleDefaultBinding || namedBindings ? updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, updateImportClause( - decl.importClause, - visibleDefaultBinding, - namedBindings - ), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + decl.importClause, + visibleDefaultBinding, + namedBindings + ), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; } // Named imports (optionally with visible default) const bindingList = mapDefined(decl.importClause.namedBindings.elements, b => resolver.isDeclarationVisible(b) ? b : undefined); @@ -1494,7 +1494,7 @@ namespace ts { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.ImportType: - return true; + return true; } return false; } diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 33465799c29..61d4dd30a67 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -228,9 +228,9 @@ namespace ts { else { diagnosticMessage = symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; } } return { @@ -353,7 +353,7 @@ namespace ts { Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccessibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 7623d19dd25..f51708eb07d 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -4106,10 +4106,8 @@ namespace ts { * Visits the `super` keyword */ function visitSuperKeyword(isExpressionOfCall: boolean): LeftHandSideExpression { - return hierarchyFacts & HierarchyFacts.NonStaticClassElement - && !isExpressionOfCall - ? createPropertyAccess(createFileLevelUniqueName("_super"), "prototype") - : createFileLevelUniqueName("_super"); + return hierarchyFacts & HierarchyFacts.NonStaticClassElement && !isExpressionOfCall ? createPropertyAccess(createFileLevelUniqueName("_super"), "prototype") : + createFileLevelUniqueName("_super"); } function visitMetaProperty(node: MetaProperty) { diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index 89c43dcf599..084bbd5d1f0 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -960,9 +960,7 @@ namespace ts { export function createAssignHelper(context: TransformationContext, attributesSegments: Expression[]) { if (context.getCompilerOptions().target! >= ScriptTarget.ES2015) { - return createCall(createPropertyAccess(createIdentifier("Object"), "assign"), - /*typeArguments*/ undefined, - attributesSegments); + return createCall(createPropertyAccess(createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments); } context.requestEmitHelper(assignHelper); return createCall( diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 2e02e15a2ed..2ef602adff8 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -175,18 +175,18 @@ namespace ts { jsonSourceFile ? jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : createObjectLiteral() : createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - [ - createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports"), - ...importAliasNames - ], - /*type*/ undefined, - transformAsynchronousModuleBody(node) - ) + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + [ + createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports"), + ...importAliasNames + ], + /*type*/ undefined, + transformAsynchronousModuleBody(node) + ) ] ) ) diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index c48d07312dd..8d9a2d91730 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -106,7 +106,7 @@ namespace ts { createExpressionStatement( createCall( createPropertyAccess(createIdentifier("System"), "register"), - /*typeArguments*/ undefined, + /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction] diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 1cb94244ffb..00bf1aecf32 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1716,7 +1716,7 @@ namespace ts { const left = serializeEntityNameAsExpressionFallback(node.left); const temp = createTempVariable(hoistVariableDeclaration); return createLogicalAnd( - createLogicalAnd( + createLogicalAnd( left.left, createStrictInequality(createAssignment(temp, left.right), createVoidZero()) ), diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 245d965582b..f7879cf54a5 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1117,7 +1117,8 @@ namespace ts { } export interface KeywordTypeNode extends TypeNode { - kind: SyntaxKind.AnyKeyword + kind: + | SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword @@ -3391,8 +3392,8 @@ namespace ts { WriteClassExpressionAsTypeLiteral = 1 << 11, // Write a type literal instead of (Anonymous class) UseTypeOfFunction = 1 << 12, // Write typeof instead of function type literal OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters - UseAliasDefinedOutsideCurrentScope = 1 << 14, // For a `type T = ... ` defined in a different file, write `T` instead of its value, - // even though `T` can't be accessed in the current scope. + + UseAliasDefinedOutsideCurrentScope = 1 << 14, // For a `type T = ... ` defined in a different file, write `T` instead of its value, even though `T` can't be accessed in the current scope. // Error Handling AllowUniqueESSymbolType = 1 << 20, // This is bit 20 to align with the same bit in `NodeBuilderFlags` @@ -3409,8 +3410,7 @@ namespace ts { /** @deprecated */ WriteOwnNameForAnyLike = 0, // Does nothing - NodeBuilderFlagsMask = - NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature | + NodeBuilderFlagsMask = NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature | UseFullyQualifiedType | SuppressAnyReturnType | MultilineObjectLiterals | WriteClassExpressionAsTypeLiteral | UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias, } @@ -3555,23 +3555,45 @@ namespace ts { /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */ /* @internal */ export enum TypeReferenceSerializationKind { - Unknown, // The TypeReferenceNode could not be resolved. The type name - // should be emitted using a safe fallback. - TypeWithConstructSignatureAndValue, // The TypeReferenceNode resolves to a type with a constructor - // function that can be reached at runtime (e.g. a `class` - // declaration or a `var` declaration for the static side - // of a type, such as the global `Promise` type in lib.d.ts). - VoidNullableOrNeverType, // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type. - NumberLikeType, // The TypeReferenceNode resolves to a Number-like type. - BigIntLikeType, // The TypeReferenceNode resolves to a BigInt-like type. - StringLikeType, // The TypeReferenceNode resolves to a String-like type. - BooleanType, // The TypeReferenceNode resolves to a Boolean-like type. - ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type. - ESSymbolType, // The TypeReferenceNode resolves to the ESSymbol type. - Promise, // The TypeReferenceNode resolved to the global Promise constructor symbol. - TypeWithCallSignature, // The TypeReferenceNode resolves to a Function type or a type - // with call signatures. - ObjectType, // The TypeReferenceNode resolves to any other type. + // The TypeReferenceNode could not be resolved. + // The type name should be emitted using a safe fallback. + Unknown, + + // The TypeReferenceNode resolves to a type with a constructor + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). + TypeWithConstructSignatureAndValue, + + // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type. + VoidNullableOrNeverType, + + // The TypeReferenceNode resolves to a Number-like type. + NumberLikeType, + + // The TypeReferenceNode resolves to a BigInt-like type. + BigIntLikeType, + + // The TypeReferenceNode resolves to a String-like type. + StringLikeType, + + // The TypeReferenceNode resolves to a Boolean-like type. + BooleanType, + + // The TypeReferenceNode resolves to an Array-like type. + ArrayLikeType, + + // The TypeReferenceNode resolves to the ESSymbol type. + ESSymbolType, + + // The TypeReferenceNode resolved to the global Promise constructor symbol. + Promise, + + // The TypeReferenceNode resolves to a Function type or a type with call signatures. + TypeWithCallSignature, + + // The TypeReferenceNode resolves to any other type. + ObjectType, } /* @internal */ @@ -5613,9 +5635,13 @@ namespace ts { } /*@internal*/ - export type BundleFileSection = BundleFilePrologue | BundleFileEmitHelpers | - BundleFileHasNoDefaultLib | BundleFileReference | BundleFilePrepend | - BundleFileTextLike; + export type BundleFileSection = + BundleFilePrologue + | BundleFileEmitHelpers + | BundleFileHasNoDefaultLib + | BundleFileReference + | BundleFilePrepend + | BundleFileTextLike; /*@internal*/ export interface SourceFilePrologueDirectiveExpression extends TextRange { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 7215fad76ff..d90a025b6bc 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1252,7 +1252,7 @@ namespace ts { export function isValidESSymbolDeclaration(node: Node): node is VariableDeclaration | PropertyDeclaration | SignatureDeclaration { return isVariableDeclaration(node) ? isVarConst(node) && isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : - isPropertySignature(node) && hasReadonlyModifier(node); + isPropertySignature(node) && hasReadonlyModifier(node); } export function introducesArgumentsExoticObject(node: Node) { @@ -1917,7 +1917,7 @@ namespace ts { export function isDefaultedExpandoInitializer(node: BinaryExpression) { const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken ? node.parent.left : - undefined; + undefined; return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } @@ -1984,13 +1984,13 @@ namespace ts { } export function isBindableObjectDefinePropertyCall(expr: CallExpression): expr is BindableObjectDefinePropertyCall { - return length(expr.arguments) === 3 && - isPropertyAccessExpression(expr.expression) && - isIdentifier(expr.expression.expression) && - idText(expr.expression.expression) === "Object" && - idText(expr.expression.name) === "defineProperty" && - isStringOrNumericLiteralLike(expr.arguments[1]) && - isEntityNameExpression(expr.arguments[0]); + return length(expr.arguments) === 3 && + isPropertyAccessExpression(expr.expression) && + isIdentifier(expr.expression.expression) && + idText(expr.expression.expression) === "Object" && + idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); } function getAssignmentDeclarationKindWorker(expr: BinaryExpression | CallExpression): AssignmentDeclarationKind { @@ -2013,8 +2013,8 @@ namespace ts { } const lhs = expr.left; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { - // F.prototype = { ... } - return AssignmentDeclarationKind.Prototype; + // F.prototype = { ... } + return AssignmentDeclarationKind.Prototype; } return getAssignmentDeclarationPropertyAccessKind(lhs); } @@ -2593,9 +2593,9 @@ namespace ts { /** Returns the node in an `extends` or `implements` clause of a class or interface. */ export function getAllSuperTypeNodes(node: Node): ReadonlyArray { - return isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || emptyArray - : isClassLike(node) ? concatenate(singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || emptyArray - : emptyArray; + return isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || emptyArray : + isClassLike(node) ? concatenate(singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || emptyArray : + emptyArray; } export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration) { @@ -2646,7 +2646,8 @@ namespace ts { return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); } - export type TriviaKind = SyntaxKind.SingleLineCommentTrivia + export type TriviaKind = + SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia @@ -3141,8 +3142,8 @@ namespace ts { export function escapeString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote | CharacterCodes.backtick): string { const escapedCharsRegExp = quoteChar === CharacterCodes.backtick ? backtickQuoteEscapedCharsRegExp : - quoteChar === CharacterCodes.singleQuote ? singleQuoteEscapedCharsRegExp : - doubleQuoteEscapedCharsRegExp; + quoteChar === CharacterCodes.singleQuote ? singleQuoteEscapedCharsRegExp : + doubleQuoteEscapedCharsRegExp; return s.replace(escapedCharsRegExp, getReplacement); } @@ -4331,7 +4332,7 @@ namespace ts { const checkFlags = (s).checkFlags; const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private : checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public : - ModifierFlags.Protected; + ModifierFlags.Protected; const staticModifier = checkFlags & CheckFlags.ContainsStatic ? ModifierFlags.Static : 0; return accessModifier | staticModifier; } @@ -5383,10 +5384,9 @@ namespace ts { } export function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined { - return node.constraint ? node.constraint - : isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] - ? node.parent.constraint - : undefined; + return node.constraint ? node.constraint : + isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint : + undefined; } } diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index afc03e5b4be..c06fcd4f655 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -232,7 +232,6 @@ namespace ts { visitNode((node).expression, visitor, isExpression)); // Signature elements - case SyntaxKind.TypeParameter: return updateTypeParameterDeclaration(node, visitNode((node).name, visitor, isIdentifier), @@ -254,7 +253,6 @@ namespace ts { visitNode((node).expression, visitor, isExpression)); // Type elements - case SyntaxKind.PropertySignature: return updatePropertySignature((node), nodesVisitor((node).modifiers, visitor, isToken), @@ -337,7 +335,6 @@ namespace ts { visitNode((node).type, visitor, isTypeNode)); // Types - case SyntaxKind.TypePredicate: return updateTypePredicateNode(node, visitNode((node).parameterName, visitor), @@ -436,7 +433,6 @@ namespace ts { visitNode((node).literal, visitor, isExpression)); // Binding patterns - case SyntaxKind.ObjectBindingPattern: return updateObjectBindingPattern(node, nodesVisitor((node).elements, visitor, isBindingElement)); @@ -453,7 +449,6 @@ namespace ts { visitNode((node).initializer, visitor, isExpression)); // Expression - case SyntaxKind.ArrayLiteralExpression: return updateArrayLiteral(node, nodesVisitor((node).elements, visitor, isExpression)); @@ -597,14 +592,12 @@ namespace ts { visitNode((node).name, visitor, isIdentifier)); // Misc - case SyntaxKind.TemplateSpan: return updateTemplateSpan(node, visitNode((node).expression, visitor, isExpression), visitNode((node).literal, visitor, isTemplateMiddleOrTemplateTail)); // Element - case SyntaxKind.Block: return updateBlock(node, nodesVisitor((node).statements, visitor, isStatement)); @@ -819,13 +812,11 @@ namespace ts { visitNode((node).name, visitor, isIdentifier)); // Module references - case SyntaxKind.ExternalModuleReference: return updateExternalModuleReference(node, visitNode((node).expression, visitor, isExpression)); // JSX - case SyntaxKind.JsxElement: return updateJsxElement(node, visitNode((node).openingElement, visitor, isJsxOpeningElement), @@ -872,7 +863,6 @@ namespace ts { visitNode((node).expression, visitor, isExpression)); // Clauses - case SyntaxKind.CaseClause: return updateCaseClause(node, visitNode((node).expression, visitor, isExpression), @@ -892,7 +882,6 @@ namespace ts { visitNode((node).block, visitor, isBlock)); // Property assignments - case SyntaxKind.PropertyAssignment: return updatePropertyAssignment(node, visitNode((node).name, visitor, isPropertyName), @@ -1017,7 +1006,6 @@ namespace ts { break; // Type member - case SyntaxKind.PropertySignature: result = reduceNodes((node).modifiers, cbNodes, result); result = reduceNode((node).name, cbNode, result); diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index d8af9bade36..aae90bf34b4 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -735,9 +735,10 @@ namespace ts { compilerHost.writeLog = writeLog; // Cache for the module resolution - const resolutionCache = createResolutionCache(compilerHost, configFileName ? - getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : - currentDirectory, + const resolutionCache = createResolutionCache(compilerHost, + configFileName ? + getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, /*logChangesWhenResolvingModule*/ false ); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index b0b20c92e64..eadad71b610 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -128,8 +128,8 @@ class TypeWriterWalker { !this.isImportStatementName(node) && !this.isExportStatementName(node) && !this.isIntrinsicJsxTag(node)) ? - (type as ts.IntrinsicType).intrinsicName : - this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.AllowUniqueESSymbolType); + (type as ts.IntrinsicType).intrinsicName : + this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.AllowUniqueESSymbolType); return { line: lineAndCharacter.line, syntaxKind: node.kind, diff --git a/src/lib/es2019.array.d.ts b/src/lib/es2019.array.d.ts index 07fc76a9c77..3240da61025 100644 --- a/src/lib/es2019.array.d.ts +++ b/src/lib/es2019.array.d.ts @@ -98,10 +98,7 @@ interface ReadonlyArray { * * @param depth The maximum recursion depth */ - flat(this: - ReadonlyArray, - depth: 0 - ): U[]; + flat(this: ReadonlyArray, depth: 0): U[]; /** * Returns a new array with all sub-array elements concatenated into it recursively up to the @@ -110,7 +107,7 @@ interface ReadonlyArray { * @param depth The maximum recursion depth */ flat(depth?: number): any[]; - } +} interface Array { diff --git a/src/lib/es2019.string.d.ts b/src/lib/es2019.string.d.ts index 9d97779745f..b83472b11ab 100644 --- a/src/lib/es2019.string.d.ts +++ b/src/lib/es2019.string.d.ts @@ -1,13 +1,13 @@ interface String { - /** Removes the trailing white space and line terminator characters from a string. */ - trimEnd(): string; + /** Removes the trailing white space and line terminator characters from a string. */ + trimEnd(): string; - /** Removes the leading white space and line terminator characters from a string. */ - trimStart(): string; + /** Removes the leading white space and line terminator characters from a string. */ + trimStart(): string; - /** Removes the leading white space and line terminator characters from a string. */ - trimLeft(): string; + /** Removes the leading white space and line terminator characters from a string. */ + trimLeft(): string; - /** Removes the trailing white space and line terminator characters from a string. */ - trimRight(): string; + /** Removes the trailing white space and line terminator characters from a string. */ + trimRight(): string; } diff --git a/src/lib/es2020.string.d.ts b/src/lib/es2020.string.d.ts index 335a0ac0005..8602729e750 100644 --- a/src/lib/es2020.string.d.ts +++ b/src/lib/es2020.string.d.ts @@ -1,10 +1,10 @@ /// interface String { - /** - * Matches a string with a regular expression, and returns an iterable of matches - * containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - matchAll(regexp: RegExp): IterableIterator; + /** + * Matches a string with a regular expression, and returns an iterable of matches + * containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + matchAll(regexp: RegExp): IterableIterator; } diff --git a/src/lib/es2020.symbol.wellknown.d.ts b/src/lib/es2020.symbol.wellknown.d.ts index 76e377e0be2..08e1fa2c913 100644 --- a/src/lib/es2020.symbol.wellknown.d.ts +++ b/src/lib/es2020.symbol.wellknown.d.ts @@ -2,18 +2,18 @@ /// interface SymbolConstructor { - /** - * A regular expression method that matches the regular expression against a string. Called - * by the String.prototype.matchAll method. - */ - readonly matchAll: symbol; + /** + * A regular expression method that matches the regular expression against a string. Called + * by the String.prototype.matchAll method. + */ + readonly matchAll: symbol; } interface RegExp { - /** - * Matches a string with this regular expression, and returns an iterable of matches - * containing the results of that search. - * @param string A string to search within. - */ - [Symbol.matchAll](str: string): IterableIterator; + /** + * Matches a string with this regular expression, and returns an iterable of matches + * containing the results of that search. + * @param string A string to search within. + */ + [Symbol.matchAll](str: string): IterableIterator; } diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 0d1481dd7d2..d4df68e2c50 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -75,11 +75,11 @@ declare function escape(string: string): string; declare function unescape(string: string): string; interface Symbol { - /** Returns a string representation of an object. */ - toString(): string; + /** Returns a string representation of an object. */ + toString(): string; - /** Returns the primitive value of the specified object. */ - valueOf(): symbol; + /** Returns the primitive value of the specified object. */ + valueOf(): symbol; } declare type PropertyKey = string | number | symbol; @@ -238,7 +238,7 @@ interface ObjectConstructor { * Returns the names of the enumerable string properties and methods of an object. * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - keys(o: object): string[]; + keys(o: object): string[]; } /** diff --git a/src/lib/esnext.intl.d.ts b/src/lib/esnext.intl.d.ts index 99e202bd91b..ed793ed98ff 100644 --- a/src/lib/esnext.intl.d.ts +++ b/src/lib/esnext.intl.d.ts @@ -9,4 +9,4 @@ declare namespace Intl { interface NumberFormat { formatToParts(number?: number): NumberFormatPart[]; } - } +} diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index b773fca8ea8..9f0e687431b 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -50,24 +50,25 @@ namespace ts.server { readonly data: ProjectInfoTelemetryEventData; } -/* __GDPR__ - "projectInfo" : { - "${include}": ["${TypeScriptCommonProperties}"], - "projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" }, - "fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } - } - */ + /** + * __GDPR__ + * "projectInfo" : { + * "${include}": ["${TypeScriptCommonProperties}"], + * "projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" }, + * "fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + * } + */ export interface ProjectInfoTelemetryEventData { /** Cryptographically secure hash of project file location. */ readonly projectId: string; @@ -139,14 +140,15 @@ namespace ts.server { readonly checkJs: boolean; } - export type ProjectServiceEvent = LargeFileReferencedEvent | - ProjectsUpdatedInBackgroundEvent | - ProjectLoadingStartEvent | - ProjectLoadingFinishEvent | - ConfigFileDiagEvent | - ProjectLanguageServiceStateEvent | - ProjectInfoTelemetryEvent | - OpenFileInfoTelemetryEvent; + export type ProjectServiceEvent = + LargeFileReferencedEvent + | ProjectsUpdatedInBackgroundEvent + | ProjectLoadingStartEvent + | ProjectLoadingFinishEvent + | ConfigFileDiagEvent + | ProjectLanguageServiceStateEvent + | ProjectInfoTelemetryEvent + | OpenFileInfoTelemetryEvent; export type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; @@ -2325,7 +2327,7 @@ namespace ts.server { this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); declarationInfo.closeSourceMapFileWatcher(); } - }, + }, PollingInterval.High, WatchType.MissingSourceMapFile, ); diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 98f48661e99..38115c0a81a 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2188,9 +2188,9 @@ namespace ts.server.protocol { export type SignatureHelpTriggerCharacter = "," | "(" | "<"; export type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; - /** - * Arguments of a signature help request. - */ + /** + * Arguments of a signature help request. + */ export interface SignatureHelpRequestArgs extends FileLocationRequestArgs { /** * Reason why signature help was invoked. @@ -2586,8 +2586,17 @@ namespace ts.server.protocol { } /*@internal*/ - export type AnyEvent = RequestCompletedEvent | DiagnosticEvent | ConfigFileDiagnosticEvent | ProjectLanguageServiceStateEvent | TelemetryEvent | - ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | SurveyReadyEvent | LargeFileReferencedEvent; + export type AnyEvent = + RequestCompletedEvent + | DiagnosticEvent + | ConfigFileDiagnosticEvent + | ProjectLanguageServiceStateEvent + | TelemetryEvent + | ProjectsUpdatedInBackgroundEvent + | ProjectLoadingStartEvent + | ProjectLoadingFinishEvent + | SurveyReadyEvent + | LargeFileReferencedEvent; /** * Arguments for reload request. @@ -2848,14 +2857,15 @@ namespace ts.server.protocol { payload: TypingsInstalledTelemetryEventPayload; } -/* __GDPR__ - "typingsinstalled" : { - "${include}": ["${TypeScriptCommonProperties}"], - "installedPackages": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, - "installSuccess": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, - "typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } - } - */ + /** + * __GDPR__ + * "typingsinstalled" : { + * "${include}": ["${TypeScriptCommonProperties}"], + * "installedPackages": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, + * "installSuccess": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + * } + */ export interface TypingsInstalledTelemetryEventPayload { /** * Comma separated list of installed typing packages diff --git a/src/server/session.ts b/src/server/session.ts index ddad5807682..bc51dd54ecb 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -324,7 +324,7 @@ namespace ts.server { defaultProject, initialLocation, ({ project, location }, tryAddToTodo) => { - for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || emptyArray) { + for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || emptyArray) { if (!contains(outputs, output, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { outputs.push(output); } diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index 6c0ac8639d8..8dd9bf3539c 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -275,12 +275,10 @@ namespace ts.codefix { const moduleSpecifier = reExported.text; const moduleSymbol = checker.getSymbolAtLocation(reExported); const exports = moduleSymbol ? moduleSymbol.exports! : emptyUnderscoreEscapedMap; - return exports.has("export=" as __String) - ? [[reExportDefault(moduleSpecifier)], true] - : !exports.has("default" as __String) - ? [[reExportStar(moduleSpecifier)], false] + return exports.has("export=" as __String) ? [[reExportDefault(moduleSpecifier)], true] : + !exports.has("default" as __String) ? [[reExportStar(moduleSpecifier)], false] : // If there's some non-default export, must include both `export *` and `export default`. - : exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; + exports.size > 1 ? [[reExportStar(moduleSpecifier), reExportDefault(moduleSpecifier)], true] : [[reExportDefault(moduleSpecifier)], true]; } function reExportStar(moduleSpecifier: string): ExportDeclaration { return makeExportDeclaration(/*exportClause*/ undefined, moduleSpecifier); @@ -319,7 +317,8 @@ namespace ts.codefix { return exportConst(); } } - // falls through + + // falls through case SyntaxKind.ArrowFunction: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported as FunctionExpression | ArrowFunction); diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 59385f2e2e9..d164623b8ee 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -1,7 +1,9 @@ /* @internal */ namespace ts.codefix { - const errorCodes = [Diagnostics.Class_0_incorrectly_implements_interface_1.code, - Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code]; + const errorCodes = [ + Diagnostics.Class_0_incorrectly_implements_interface_1.code, + Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code + ]; const fixId = "fixClassIncorrectlyImplementsInterface"; // TODO: share a group with fixClassDoesntImplementInheritedAbstractMember? registerCodeFix({ errorCodes, diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 45a79613db5..71cb8b04b8a 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -153,8 +153,7 @@ namespace ts.codefix { // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker)); const names = map(args, arg => - isIdentifier(arg) ? arg.text : - isPropertyAccessExpression(arg) ? arg.name.text : undefined); + isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) ? arg.name.text : undefined); const contextualType = checker.getContextualType(call); const returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); return createMethod( diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 8006d1a0cfd..8be4d263cbb 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -285,9 +285,9 @@ namespace ts.codefix { const isJs = isSourceFileJS(sourceFile); const choicesForEachExportingModule = flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) => moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) - .map((moduleSpecifier): FixAddNewImport | FixUseImportType => - // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. - exportedSymbolIsTypeOnly && isJs ? { kind: ImportFixKind.ImportType, moduleSpecifier, position: Debug.assertDefined(position) } : { kind: ImportFixKind.AddNew, moduleSpecifier, importKind })); + .map((moduleSpecifier): FixAddNewImport | FixUseImportType => + // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. + exportedSymbolIsTypeOnly && isJs ? { kind: ImportFixKind.ImportType, moduleSpecifier, position: Debug.assertDefined(position) } : { kind: ImportFixKind.AddNew, moduleSpecifier, importKind })); // Sort to keep the shortest paths first return sort(choicesForEachExportingModule, (a, b) => a.moduleSpecifier.length - b.moduleSpecifier.length); } diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index d0aed395a0e..e7040dd2d85 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -533,7 +533,7 @@ namespace ts.codefix { break; } } - // falls through + // falls through default: return inferTypeFromContextualType(node, checker, usageContext); } diff --git a/src/services/completions.ts b/src/services/completions.ts index 96bf8d7a747..1966947432a 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -628,13 +628,13 @@ namespace ts.Completions { return isJsxExpression(parent) && parent.parent.kind !== SyntaxKind.JsxElement ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: const argInfo = SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); - return argInfo + return argInfo ? // At `,`, treat this as the next argument after the comma. - ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === SyntaxKind.CommaToken ? 1 : 0)) - : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) - // completion at `x ===/**/` should be for the right side - ? checker.getTypeAtLocation(parent.left) - : checker.getContextualType(previousToken as Expression); + checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === SyntaxKind.CommaToken ? 1 : 0)) : + isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) ? + // completion at `x ===/**/` should be for the right side + checker.getTypeAtLocation(parent.left) : + checker.getContextualType(previousToken as Expression); } } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index c77e6f497ac..711a690f33c 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -696,11 +696,9 @@ namespace ts.FindAllReferences.Core { const sourceFile = decl.getSourceFile(); if (sourceFilesSet.has(sourceFile.fileName)) { // At `module.exports = ...`, reference node is `module` - const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) - ? decl.left.expression - : isExportAssignment(decl) - ? Debug.assertDefined(findChildOfKind(decl, SyntaxKind.ExportKeyword, sourceFile)) - : getNameOfDeclaration(decl) || decl; + const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) ? decl.left.expression : + isExportAssignment(decl) ? Debug.assertDefined(findChildOfKind(decl, SyntaxKind.ExportKeyword, sourceFile)) : + getNameOfDeclaration(decl) || decl; references.push(nodeEntry(node)); } } @@ -1972,11 +1970,10 @@ namespace ts.FindAllReferences.Core { } function isImplementation(node: Node): boolean { - return !!(node.flags & NodeFlags.Ambient) - ? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node)) - : (isVariableLike(node) ? hasInitializer(node) - : isFunctionLikeDeclaration(node) ? !!node.body - : isClassLike(node) || isModuleOrEnumDeclaration(node)); + return !!(node.flags & NodeFlags.Ambient) ? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node)) : + (isVariableLike(node) ? hasInitializer(node) : + isFunctionLikeDeclaration(node) ? !!node.body : + isClassLike(node) || isModuleOrEnumDeclaration(node)); } export function getReferenceEntriesForShorthandPropertyAssignment(node: Node, checker: TypeChecker, addReference: (node: Node) => void): void { diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index b0802532c0c..7a259cab549 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -418,7 +418,7 @@ namespace ts.formatting { const leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, - item => processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!)); + item => processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!)); trimTrailingWhitespacesForRemainingRange(); } } @@ -842,7 +842,7 @@ namespace ts.formatting { if (currentTokenInfo.leadingTrivia) { const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, - item => insertIndentation(item.pos, commentIndentation, /*lineAdded*/ false)); + item => insertIndentation(item.pos, commentIndentation, /*lineAdded*/ false)); } // indent token only if is it is in target range and does not overlap with any error ranges diff --git a/src/services/formatting/formattingScanner.ts b/src/services/formatting/formattingScanner.ts index 2787f90af03..c1e97e636d0 100644 --- a/src/services/formatting/formattingScanner.ts +++ b/src/services/formatting/formattingScanner.ts @@ -138,18 +138,12 @@ namespace ts.formatting { // normally scanner returns the smallest available token // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. - const expectedScanAction = - shouldRescanGreaterThanToken(n) - ? ScanAction.RescanGreaterThanToken - : shouldRescanSlashToken(n) - ? ScanAction.RescanSlashToken - : shouldRescanTemplateToken(n) - ? ScanAction.RescanTemplateToken - : shouldRescanJsxIdentifier(n) - ? ScanAction.RescanJsxIdentifier - : shouldRescanJsxText(n) - ? ScanAction.RescanJsxText - : ScanAction.Scan; + const expectedScanAction = shouldRescanGreaterThanToken(n) ? ScanAction.RescanGreaterThanToken : + shouldRescanSlashToken(n) ? ScanAction.RescanSlashToken : + shouldRescanTemplateToken(n) ? ScanAction.RescanTemplateToken : + shouldRescanJsxIdentifier(n) ? ScanAction.RescanJsxIdentifier : + shouldRescanJsxText(n) ? ScanAction.RescanJsxText : + ScanAction.Scan; if (lastTokenInfo && expectedScanAction === lastScanAction) { // readTokenInfo was called before with the same expected scan action. @@ -276,4 +270,4 @@ namespace ts.formatting { trailingTrivia = undefined; } } -} \ No newline at end of file +} diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index b10d163343e..228e5c6fcee 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -78,11 +78,12 @@ namespace ts.formatting { // In order to insert a rule to the end of sub-bucket (3), we get the index by adding // the values in the bitmap segments 3rd, 2nd, and 1st. function addRule(rules: Rule[], rule: Rule, specificTokens: boolean, constructionState: number[], rulesBucketIndex: number): void { - const position = rule.action === RuleAction.Ignore - ? specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny - : rule.context !== anyContext - ? specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny - : specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + const position = rule.action === RuleAction.Ignore ? + specificTokens ? RulesPosition.IgnoreRulesSpecific : RulesPosition.IgnoreRulesAny : + rule.context !== anyContext ? + specificTokens ? RulesPosition.ContextRulesSpecific : RulesPosition.ContextRulesAny : + specificTokens ? RulesPosition.NoContextRulesSpecific : RulesPosition.NoContextRulesAny; + const state = constructionState[rulesBucketIndex] || 0; rules.splice(getInsertionIndex(state, position), 0, rule); constructionState[rulesBucketIndex] = increaseInsertionIndex(state, position); @@ -102,4 +103,4 @@ namespace ts.formatting { Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); } -} \ No newline at end of file +} diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index 1020c97b432..46b7ff624e4 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -134,8 +134,8 @@ namespace ts { let bestMatch: PatternMatch | undefined; for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; - i >= 0; - i -= 1, j -= 1) { + i >= 0; + i -= 1, j -= 1) { bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); } return bestMatch; @@ -590,4 +590,4 @@ namespace ts { function every(s: string, pred: (ch: number, index: number) => boolean, start = 0, end = s.length): boolean { return everyInRange(start, end, i => pred(s.charCodeAt(i), i)); } -} \ No newline at end of file +} diff --git a/src/services/refactors/convertParamsToDestructuredObject.ts b/src/services/refactors/convertParamsToDestructuredObject.ts index fa795f20a8f..f93f19b495a 100644 --- a/src/services/refactors/convertParamsToDestructuredObject.ts +++ b/src/services/refactors/convertParamsToDestructuredObject.ts @@ -266,7 +266,7 @@ namespace ts.refactor.convertParamsToDestructuredObject { const node = getTouchingToken(file, startPosition); const functionDeclaration = getContainingFunctionDeclaration(node); - // don't offer refactor on top-level JSDoc + // don't offer refactor on top-level JSDoc if (isTopLevelJSDoc(node)) return undefined; if (functionDeclaration @@ -618,4 +618,4 @@ namespace ts.refactor.convertParamsToDestructuredObject { accessExpressions: Node[]; typeUsages: Node[]; } -} \ No newline at end of file +} diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index c55acb33e1d..94ad67afe10 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -169,9 +169,9 @@ namespace ts.refactor.extractSymbol { readonly targetRange?: never; readonly errors: ReadonlyArray; } | { - readonly targetRange: TargetRange; - readonly errors?: never; - }; + readonly targetRange: TargetRange; + readonly errors?: never; + }; /* * Scopes that can store newly extracted method @@ -450,29 +450,29 @@ namespace ts.refactor.extractSymbol { rangeFacts |= RangeFacts.UsesThis; break; case SyntaxKind.LabeledStatement: { - const label = (node).label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - forEachChild(node, visit); - seenLabels.pop(); - break; - } + const label = (node).label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + forEachChild(node, visit); + seenLabels.pop(); + break; + } case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: { - const label = (node).label; - if (label) { - if (!contains(seenLabels, label.escapedText)) { - // attempts to jump to label that is not in range to be extracted - (errors || (errors = [] as Diagnostic[])).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } + const label = (node).label; + if (label) { + if (!contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [] as Diagnostic[])).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } - else { - if (!(permittedJumps & (node.kind === SyntaxKind.BreakStatement ? PermittedJumps.Break : PermittedJumps.Continue))) { - // attempt to break or continue in a forbidden context - (errors || (errors = [] as Diagnostic[])).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; } + else { + if (!(permittedJumps & (node.kind === SyntaxKind.BreakStatement ? PermittedJumps.Break : PermittedJumps.Continue))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [] as Diagnostic[])).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } case SyntaxKind.AwaitExpression: rangeFacts |= RangeFacts.IsAsyncFunction; break; diff --git a/src/services/refactors/extractType.ts b/src/services/refactors/extractType.ts index 02f6cd39a18..28a6539389c 100644 --- a/src/services/refactors/extractType.ts +++ b/src/services/refactors/extractType.ts @@ -14,8 +14,8 @@ namespace ts.refactor { actions: [info.isJS ? { name: extractToTypeDef, description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef) } : { - name: extractToTypeAlias, description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias) - }] + name: extractToTypeAlias, description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias) + }] }]; }, getEditsForAction(context, actionName): RefactorEditInfo { diff --git a/src/services/services.ts b/src/services/services.ts index db48bc7cb5d..eff02cc821c 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -5,7 +5,7 @@ namespace ts { function createNode(kind: TKind, pos: number, end: number, parent: Node): NodeObject | TokenObject | IdentifierObject { const node = isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === SyntaxKind.Identifier ? new IdentifierObject(SyntaxKind.Identifier, pos, end) : - new TokenObject(kind, pos, end); + new TokenObject(kind, pos, end); node.parent = parent; node.flags = parent.flags & NodeFlags.ContextFlags; return node; diff --git a/src/services/shims.ts b/src/services/shims.ts index 5b6ef390e57..b40a6a749a0 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -544,7 +544,7 @@ namespace ts { if (logPerformance) { const end = timestamp(); - logger.log(`${actionDescription} completed in ${end - start!} msec`); + logger.log(`${actionDescription} completed in ${end - start!} msec`); if (isString(result)) { let str = result; if (str.length > 128) { diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index b287ebdb406..e8163131977 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -220,11 +220,8 @@ namespace ts.Completions.StringCompletions { function getStringLiteralTypes(type: Type | undefined, uniques = createMap()): ReadonlyArray { if (!type) return emptyArray; type = skipConstraint(type); - return type.isUnion() - ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) - : type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) - ? [type] - : emptyArray; + return type.isUnion() ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) : + type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) ? [type] : emptyArray; } interface NameAndKind { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index f8a29985e5b..ec6e9777e25 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1753,9 +1753,8 @@ namespace ts { function getSynthesizedDeepCloneWorker(node: T, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { - const visited = (renameMap || checker || callback) ? - visitEachChild(node, wrapper, nullTransformationContext) : - visitEachChild(node, getSynthesizedDeepClone, nullTransformationContext); + const visited = (renameMap || checker || callback) ? visitEachChild(node, wrapper, nullTransformationContext) : + visitEachChild(node, getSynthesizedDeepClone, nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. diff --git a/src/testRunner/projectsRunner.ts b/src/testRunner/projectsRunner.ts index f4e51afab4c..f2b4905852c 100644 --- a/src/testRunner/projectsRunner.ts +++ b/src/testRunner/projectsRunner.ts @@ -202,7 +202,8 @@ namespace project { const ignoreCase = this.vfs.ignoreCase; const resolutionInfo: ProjectRunnerTestCaseResolutionInfo & ts.CompilerOptions = JSON.parse(JSON.stringify(this.testCase)); resolutionInfo.resolvedInputFiles = this.compilerResult.program!.getSourceFiles() - .map(({ fileName: input }) => vpath.beneath(vfs.builtFolder, input, this.vfs.ignoreCase) || vpath.beneath(vfs.testLibFolder, input, this.vfs.ignoreCase) ? utils.removeTestPathPrefixes(input) : + .map(({ fileName: input }) => + vpath.beneath(vfs.builtFolder, input, this.vfs.ignoreCase) || vpath.beneath(vfs.testLibFolder, input, this.vfs.ignoreCase) ? utils.removeTestPathPrefixes(input) : vpath.isAbsolute(input) ? vpath.relative(cwd, input, ignoreCase) : input); @@ -391,11 +392,8 @@ namespace project { } function moduleNameToString(moduleKind: ts.ModuleKind) { - return moduleKind === ts.ModuleKind.AMD - ? "amd" - : moduleKind === ts.ModuleKind.CommonJS - ? "node" - : "none"; + return moduleKind === ts.ModuleKind.AMD ? "amd" : + moduleKind === ts.ModuleKind.CommonJS ? "node" : "none"; } function getErrorsBaseline(compilerResult: CompileProjectFilesResult) { @@ -457,4 +455,4 @@ namespace project { return compilerOptions; } -} \ No newline at end of file +} diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 3d1001c7daf..4d5df0ab49b 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -83,14 +83,14 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--jsx' option must be: 'preserve', 'react-native', 'react'.", - category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + messageText: "Argument for '--jsx' option must be: 'preserve', 'react-native', 'react'.", + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, - file: undefined, - start: undefined, - length: undefined, - }], + file: undefined, + start: undefined, + length: undefined, + }], fileNames: ["0.ts"], options: {} }); @@ -109,14 +109,14 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.", - category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.", + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, - file: undefined, - start: undefined, - length: undefined, - }], + file: undefined, + start: undefined, + length: undefined, + }], fileNames: ["0.ts"], options: {} }); @@ -135,14 +135,14 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'.", - category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'.", + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, - file: undefined, - start: undefined, - length: undefined, - }], + file: undefined, + start: undefined, + length: undefined, + }], fileNames: ["0.ts"], options: {} }); @@ -161,14 +161,14 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'esnext'.", - category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'esnext'.", + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, - file: undefined, - start: undefined, - length: undefined, - }], + file: undefined, + start: undefined, + length: undefined, + }], fileNames: ["0.ts"], options: {} }); @@ -187,14 +187,14 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'.", - category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'.", + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, - file: undefined, - start: undefined, - length: undefined, - }], + file: undefined, + start: undefined, + length: undefined, + }], fileNames: ["0.ts"], options: {} }); diff --git a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts index b21f90eb448..9246bbac825 100644 --- a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts @@ -592,16 +592,16 @@ namespace ts { ] } } -`, "tsconfig.json", - { - compilerOptions: { - target: undefined, - module: ModuleKind.ESNext, - experimentalDecorators: true, - }, - hasParseErrors: true - } - ); +`, + "tsconfig.json", + { + compilerOptions: { + target: undefined, + module: ModuleKind.ESNext, + experimentalDecorators: true, + }, + hasParseErrors: true + }); }); }); } diff --git a/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts index 890cad4ade6..0c0b953209f 100644 --- a/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts +++ b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts @@ -68,7 +68,8 @@ namespace ts { exclude: ["0.js", "1.js"] }, errors: [] - }); + } + ); }); it("Convert correctly format tsconfig.json to typeAcquisition ", () => { @@ -90,7 +91,7 @@ namespace ts { exclude: ["0.js", "1.js"] }, errors: [] - }); + }); }); it("Convert incorrect format tsconfig.json to typeAcquisition ", () => { diff --git a/src/testRunner/unittests/config/showConfig.ts b/src/testRunner/unittests/config/showConfig.ts index afe8f878d27..77acbfa76d7 100644 --- a/src/testRunner/unittests/config/showConfig.ts +++ b/src/testRunner/unittests/config/showConfig.ts @@ -55,32 +55,32 @@ namespace ts { // Regression test for https://github.com/Microsoft/TypeScript/issues/28836 showTSConfigCorrectly("Show TSConfig with paths and more", ["-p", "tsconfig.json"], { - compilerOptions: { - allowJs: true, - outDir: "./lib", - esModuleInterop: true, - module: "commonjs", - moduleResolution: "node", - target: "ES2017", - sourceMap: true, - baseUrl: ".", - paths: { - "@root/*": ["./*"], - "@configs/*": ["src/configs/*"], - "@common/*": ["src/common/*"], - "*": [ - "node_modules/*", - "src/types/*" + compilerOptions: { + allowJs: true, + outDir: "./lib", + esModuleInterop: true, + module: "commonjs", + moduleResolution: "node", + target: "ES2017", + sourceMap: true, + baseUrl: ".", + paths: { + "@root/*": ["./*"], + "@configs/*": ["src/configs/*"], + "@common/*": ["src/common/*"], + "*": [ + "node_modules/*", + "src/types/*" + ] + }, + experimentalDecorators: true, + emitDecoratorMetadata: true, + resolveJsonModule: true + }, + include: [ + "./src/**/*" ] - }, - experimentalDecorators: true, - emitDecoratorMetadata: true, - resolveJsonModule: true - }, - include: [ - "./src/**/*" - ] -}); + }); // Bulk validation of all option declarations for (const option of optionDeclarations) { diff --git a/src/testRunner/unittests/config/tsconfigParsing.ts b/src/testRunner/unittests/config/tsconfigParsing.ts index 638a394a34e..5e15bbc6e9f 100644 --- a/src/testRunner/unittests/config/tsconfigParsing.ts +++ b/src/testRunner/unittests/config/tsconfigParsing.ts @@ -137,7 +137,7 @@ namespace ts { "xx\\\\" // end of line comment ] }`, { config: { exclude: ["xx\\"] } }); - }); + }); it("returns object with error when json is invalid", () => { const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", "invalid"); diff --git a/src/testRunner/unittests/jsDocParsing.ts b/src/testRunner/unittests/jsDocParsing.ts index 941b1557450..925e34b3afb 100644 --- a/src/testRunner/unittests/jsDocParsing.ts +++ b/src/testRunner/unittests/jsDocParsing.ts @@ -67,7 +67,7 @@ namespace ts { parsesCorrectly("tsFunctionType", "{() => string}"); parsesCorrectly("typeArgumentsNotFollowingDot", "{a<>}"); parsesCorrectly("functionTypeWithTrailingComma", "{function(a,)}"); - }); + }); describe("parsesIncorrectly", () => { parsesIncorrectly("emptyType", "{}"); @@ -111,39 +111,39 @@ namespace ts { describe("parsesIncorrectly", () => { parsesIncorrectly("multipleTypes", - `/** + `/** * @type {number} * @type {string} */`); parsesIncorrectly("multipleReturnTypes", - `/** + `/** * @return {number} * @return {string} */`); parsesIncorrectly("noTypeParameters", - `/** + `/** * @template */`); parsesIncorrectly("trailingTypeParameterComma", - `/** + `/** * @template T, */`); parsesIncorrectly("paramWithoutName", - `/** + `/** * @param {number} */`); parsesIncorrectly("paramWithoutTypeOrName", - `/** + `/** * @param */`); parsesIncorrectly("noType", -`/** + `/** * @type */`); parsesIncorrectly("@augments with no type", -`/** + `/** * @augments */`); }); @@ -152,166 +152,166 @@ namespace ts { parsesCorrectly("threeAsterisks", "/*** */"); parsesCorrectly("emptyComment", "/***/"); parsesCorrectly("noLeadingAsterisk", -`/** + `/** @type {number} */`); parsesCorrectly("noReturnType", -`/** + `/** * @return */`); parsesCorrectly("leadingAsterisk", -`/** + `/** * @type {number} */`); parsesCorrectly("asteriskAfterPreamble", "/** * @type {number} */"); parsesCorrectly("typeTag", -`/** + `/** * @type {number} */`); parsesCorrectly("returnTag1", -`/** + `/** * @return {number} */`); parsesCorrectly("returnTag2", -`/** + `/** * @return {number} Description text follows */`); parsesCorrectly("returnsTag1", -`/** + `/** * @returns {number} */`); parsesCorrectly("oneParamTag", -`/** + `/** * @param {number} name1 */`); parsesCorrectly("twoParamTag2", -`/** + `/** * @param {number} name1 * @param {number} name2 */`); parsesCorrectly("paramTag1", -`/** + `/** * @param {number} name1 Description text follows */`); parsesCorrectly("paramTagBracketedName1", -`/** + `/** * @param {number} [name1] Description text follows */`); parsesCorrectly("paramTagBracketedName2", -`/** + `/** * @param {number} [ name1 = 1] Description text follows */`); parsesCorrectly("twoParamTagOnSameLine", -`/** + `/** * @param {number} name1 @param {number} name2 */`); parsesCorrectly("paramTagNameThenType1", -`/** + `/** * @param name1 {number} */`); parsesCorrectly("paramTagNameThenType2", -`/** + `/** * @param name1 {number} Description */`); parsesCorrectly("argSynonymForParamTag", -`/** + `/** * @arg {number} name1 Description */`); parsesCorrectly("argumentSynonymForParamTag", -`/** + `/** * @argument {number} name1 Description */`); parsesCorrectly("templateTag", -`/** + `/** * @template T */`); parsesCorrectly("templateTag2", -`/** + `/** * @template K,V */`); parsesCorrectly("templateTag3", -`/** + `/** * @template K ,V */`); parsesCorrectly("templateTag4", -`/** + `/** * @template K, V */`); parsesCorrectly("templateTag5", -`/** + `/** * @template K , V */`); parsesCorrectly("templateTag6", -`/** + `/** * @template K , V Description of type parameters. */`); parsesCorrectly("paramWithoutType", -`/** + `/** * @param foo */`); parsesCorrectly("typedefTagWithChildrenTags", -`/** + `/** * @typedef People * @type {Object} * @property {number} age * @property {string} name */`); parsesCorrectly("less-than and greater-than characters", -`/** + `/** * @param x hi < > still part of the previous comment */`); parsesCorrectly("Nested @param tags", -`/** + `/** * @param {object} o Doc doc * @param {string} o.f Doc for f */`); parsesCorrectly("@link tags", -`/** + `/** * {@link first link} * Inside {@link link text} thing * @see {@link second link text} and {@link Foo|a foo} as well. diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 6194b2b55b0..bae44b71d20 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -1102,7 +1102,7 @@ import b = require("./moduleB"); paths: { "libs/guid": [ "src/libs/guid" ] } - }; + }; const result = resolveModuleName("libs/guid", app.name, options, host); checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(libsTypings.name), [ // first try to load module as file diff --git a/src/testRunner/unittests/printer.ts b/src/testRunner/unittests/printer.ts index 0dcf32672d4..1605e7edc60 100644 --- a/src/testRunner/unittests/printer.ts +++ b/src/testRunner/unittests/printer.ts @@ -124,9 +124,8 @@ namespace ts { EmitHint.Unspecified, createNew( createPropertyAccess( - createCall( - createIdentifier("f"), /*typeArguments*/ undefined, /*argumentsArray*/ undefined), - "x"), + createCall(createIdentifier("f"), /*typeArguments*/ undefined, /*argumentsArray*/ undefined), + "x"), /*typeArguments*/ undefined, /*argumentsArray*/ undefined ), diff --git a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts index 9868d628d0c..bd8ed2714ac 100644 --- a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts +++ b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts @@ -8,22 +8,19 @@ namespace ts { `; it("can cancel signature help mid-request", () => { verifyOperationCancelledAfter(file, 4, service => // Two calls are top-level in services, one is the root type, and the second should be for the parameter type - service.getSignatureHelpItems("file.ts", file.lastIndexOf("f"), emptyOptions)!, - r => assert.exists(r.items[0]) + service.getSignatureHelpItems("file.ts", file.lastIndexOf("f"), emptyOptions)!, r => assert.exists(r.items[0]) ); }); it("can cancel find all references mid-request", () => { verifyOperationCancelledAfter(file, 3, service => // Two calls are top-level in services, one is the root type - service.findReferences("file.ts", file.lastIndexOf("o"))!, - r => assert.exists(r[0].definition) + service.findReferences("file.ts", file.lastIndexOf("o"))!, r => assert.exists(r[0].definition) ); }); it("can cancel quick info mid-request", () => { verifyOperationCancelledAfter(file, 1, service => // The LS doesn't do any top-level checks on the token for quickinfo, so the first check is within the checker - service.getQuickInfoAtPosition("file.ts", file.lastIndexOf("o"))!, - r => assert.exists(r.displayParts) + service.getQuickInfoAtPosition("file.ts", file.lastIndexOf("o"))!, r => assert.exists(r.displayParts) ); }); @@ -50,18 +47,13 @@ namespace ts { placeOpenBraceOnNewLineForControlBlocks: false, }; verifyOperationCancelledAfter(file, 1, service => // The LS doesn't do any top-level checks on the token for completion entry details, so the first check is within the checker - service.getCompletionEntryDetails("file.ts", file.lastIndexOf("f"), "foo", options, /*content*/ undefined, {})!, - r => assert.exists(r.displayParts) + service.getCompletionEntryDetails("file.ts", file.lastIndexOf("f"), "foo", options, /*content*/ undefined, {})!, r => assert.exists(r.displayParts) ); }); it("can cancel suggestion diagnostics mid-request", () => { verifyOperationCancelledAfter(file, 1, service => // The LS doesn't do any top-level checks on the token for suggestion diagnostics, so the first check is within the checker - service.getSuggestionDiagnostics("file.js"), - r => assert.notEqual(r.length, 0), - "file.js", - "function foo() { let a = 10; }", - { allowJs: true } + service.getSuggestionDiagnostics("file.js"), r => assert.notEqual(r.length, 0), "file.js", "function foo() { let a = 10; }", { allowJs: true } ); }); }); diff --git a/src/testRunner/unittests/services/colorization.ts b/src/testRunner/unittests/services/colorization.ts index 91730af33a6..0ee55d65eb0 100644 --- a/src/testRunner/unittests/services/colorization.ts +++ b/src/testRunner/unittests/services/colorization.ts @@ -385,7 +385,7 @@ describe("unittests:: services:: Colorization", () => { it("LexicallyClassifiesConflictTokens", () => { // Test conflict markers. testLexicalClassification( -"class C {\r\n\ + "class C {\r\n\ <<<<<<< HEAD\r\n\ v = 1;\r\n\ =======\r\n\ @@ -407,7 +407,7 @@ describe("unittests:: services:: Colorization", () => { finalEndOfLineState(ts.EndOfLineState.None)); testLexicalClassification( -"<<<<<<< HEAD\r\n\ + "<<<<<<< HEAD\r\n\ class C { }\r\n\ =======\r\n\ class D { }\r\n\ @@ -423,7 +423,7 @@ class D { }\r\n\ finalEndOfLineState(ts.EndOfLineState.None)); testLexicalClassification( -"class C {\r\n\ + "class C {\r\n\ <<<<<<< HEAD\r\n\ v = 1;\r\n\ ||||||| merged common ancestors\r\n\ @@ -448,7 +448,7 @@ class D { }\r\n\ finalEndOfLineState(ts.EndOfLineState.None)); testLexicalClassification( -"<<<<<<< HEAD\r\n\ + "<<<<<<< HEAD\r\n\ class C { }\r\n\ ||||||| merged common ancestors\r\n\ class E { }\r\n\ diff --git a/src/testRunner/unittests/services/convertToAsyncFunction.ts b/src/testRunner/unittests/services/convertToAsyncFunction.ts index 82a404297a3..10d44c2453b 100644 --- a/src/testRunner/unittests/services/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/services/convertToAsyncFunction.ts @@ -366,11 +366,11 @@ function [#|f|](): Promise{ const result = getResult(); return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) }); }`); - _testConvertToAsyncFunction("convertToAsyncFunction_basicNoReturnTypeAnnotation", ` + _testConvertToAsyncFunction("convertToAsyncFunction_basicNoReturnTypeAnnotation", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(result => { console.log(result) }); }`); - _testConvertToAsyncFunction("convertToAsyncFunction_basicWithComments", ` + _testConvertToAsyncFunction("convertToAsyncFunction_basicWithComments", ` function [#|f|](): Promise{ /* Note - some of these comments are removed during the refactor. This is not ideal. */ @@ -383,7 +383,7 @@ function [#|f|](): Promise{ [#|():Promise => {|] return fetch('https://typescriptlang.org').then(result => console.log(result)); }`); - _testConvertToAsyncFunction("convertToAsyncFunction_ArrowFunctionNoAnnotation", ` + _testConvertToAsyncFunction("convertToAsyncFunction_ArrowFunctionNoAnnotation", ` [#|() => {|] return fetch('https://typescriptlang.org').then(result => console.log(result)); }`); @@ -797,7 +797,7 @@ function my_print (resp) { ` ); -_testConvertToAsyncFunction("convertToAsyncFunction_Param2", ` + _testConvertToAsyncFunction("convertToAsyncFunction_Param2", ` function [#|f|]() { return my_print(fetch("https://typescriptlang.org").then(res => console.log(res))).catch(err => console.log("Error!", err)); } @@ -948,7 +948,7 @@ function rej(reject){ ` ); -_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes01", ` + _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes01", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -979,7 +979,7 @@ function rej(reject){ ); -_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02", ` + _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res => 0).catch(rej => 1).then(res); } @@ -990,7 +990,7 @@ function res(result): number { ` ); -_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02NoAnnotations", ` + _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02NoAnnotations", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res => 0).catch(rej => 1).then(res); } @@ -999,7 +999,7 @@ function res(result){ return 5; } ` -); + ); _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes01", ` function [#|f|](){ @@ -1016,7 +1016,7 @@ function rej(reject){ ` ); -_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02", ` + _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1031,7 +1031,7 @@ function rej(reject): Response{ ` ); -_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02NoAnnotations", ` + _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02NoAnnotations", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1047,7 +1047,7 @@ function rej(reject){ ); -_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes03", ` + _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes03", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).then(res); } @@ -1062,7 +1062,7 @@ function rej(reject){ ` ); -_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes04", ` + _testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes04", ` interface a { name: string; age: number; @@ -1097,13 +1097,13 @@ function [#|f|]() { } `); - _testConvertToAsyncFunction("convertToAsyncFunction_PromiseCallInner", ` + _testConvertToAsyncFunction("convertToAsyncFunction_PromiseCallInner", ` function [#|f|]() { return fetch(Promise.resolve(1).then(res => "https://typescriptlang.org")).catch(err => console.log(err)); } `); -_testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchFollowedByCall", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchFollowedByCall", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).toString(); } @@ -1118,7 +1118,6 @@ function rej(reject){ ` ); - _testConvertToAsyncFunction("convertToAsyncFunction_Scope2", ` function [#|f|](){ var i:number; @@ -1179,7 +1178,7 @@ function [#|f|]() { } `); - _testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", ` + _testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", ` function f() { function fn2(){ function [#|fn3|](){ @@ -1204,43 +1203,43 @@ function [#|f|]() { } `); - _testConvertToAsyncFunction("convertToAsyncFunction_ResRejNoArgsArrow", ` + _testConvertToAsyncFunction("convertToAsyncFunction_ResRejNoArgsArrow", ` function [#|f|]() { return Promise.resolve().then(() => 1, () => "a"); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpression", ` + _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpression", ` const [#|foo|] = function () { return fetch('https://typescriptlang.org').then(result => { console.log(result) }); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionWithName", ` + _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionWithName", ` const foo = function [#|f|]() { return fetch('https://typescriptlang.org').then(result => { console.log(result) }); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionAssignedToBindingPattern", ` + _testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionAssignedToBindingPattern", ` const { length } = [#|function|] () { return fetch('https://typescriptlang.org').then(result => { console.log(result) }); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", ` + _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", ` function [#|f|]() { return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParamsBindingPattern", ` + _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParamsBindingPattern", ` function [#|f|]() { return Promise.resolve().then(() => ({ x: 3 })).catch(() => ({ x: "a" })).then(({ x }) => !!x); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", ` + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(res); } @@ -1249,7 +1248,7 @@ function res({ status, trailer }){ } `); - _testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", ` + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", ` function [#|f|]() { const result = 'https://typescriptlang.org'; return fetch(result).then(res); @@ -1259,19 +1258,19 @@ function res({ status, trailer }){ } `); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", ` function [#|f|]() { return Promise.resolve().then(f ? (x => x) : (y => y)); } `); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", ` function [#|f|]() { return Promise.resolve().then(f ? (x => x) : (y => y)).then(q => q); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_runEffectfulContinuation", ` + _testConvertToAsyncFunction("convertToAsyncFunction_runEffectfulContinuation", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(res).then(_ => console.log("done")); } @@ -1280,31 +1279,31 @@ function res(result) { } `); - _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromise", ` + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromise", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length)).then(x => console.log(x + 5)); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseInBlock", ` + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseInBlock", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(s => { return Promise.resolve(s.statusText.length) }).then(x => x + 5); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsFixablePromise", ` + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsFixablePromise", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText).then(st => st.length)).then(x => console.log(x + 5)); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseLastInChain", ` + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseLastInChain", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length)); } `); - _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsRejectedPromiseInTryBlock", ` + _testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsRejectedPromiseInTryBlock", ` function [#|f|]() { return Promise.resolve(1) .then(x => Promise.reject(x)) @@ -1312,12 +1311,13 @@ function [#|f|]() { } `); -_testConvertToAsyncFunction("convertToAsyncFunction_nestedPromises", ` + _testConvertToAsyncFunction("convertToAsyncFunction_nestedPromises", ` function [#|f|]() { return fetch('https://typescriptlang.org').then(x => Promise.resolve(3).then(y => Promise.resolve(x.statusText.length + y))); } `); -_testConvertToAsyncFunction("convertToAsyncFunction_noArgs", ` + + _testConvertToAsyncFunction("convertToAsyncFunction_noArgs", ` function delay(millis: number): Promise { throw "no" } @@ -1330,13 +1330,14 @@ function [#|main2|]() { .then(() => { console.log("."); return delay(500); }) } `); -_testConvertToAsyncFunction("convertToAsyncFunction_exportModifier", ` + + _testConvertToAsyncFunction("convertToAsyncFunction_exportModifier", ` export function [#|foo|]() { return fetch('https://typescriptlang.org').then(s => console.log(s)); } `); -_testConvertToAsyncFunction("convertToAsyncFunction_OutermostOnlySuccess", ` + _testConvertToAsyncFunction("convertToAsyncFunction_OutermostOnlySuccess", ` function [#|foo|]() { return fetch('a').then(() => { return fetch('b').then(() => 'c'); @@ -1344,7 +1345,7 @@ function [#|foo|]() { } `); -_testConvertToAsyncFunctionFailedSuggestion("convertToAsyncFunction_OutermostOnlyFailure", ` + _testConvertToAsyncFunctionFailedSuggestion("convertToAsyncFunction_OutermostOnlyFailure", ` function foo() { return fetch('a').then([#|() => {|] return fetch('b').then(() => 'c'); diff --git a/src/testRunner/unittests/services/extract/functions.ts b/src/testRunner/unittests/services/extract/functions.ts index d872ad81a63..6f7eecce05a 100644 --- a/src/testRunner/unittests/services/extract/functions.ts +++ b/src/testRunner/unittests/services/extract/functions.ts @@ -220,7 +220,7 @@ namespace ts { }`, /*includeLib*/ true); testExtractFunction("extractFunction20", - `const _ = class { + `const _ = class { a() { [#|let a1 = { x: 1 }; return a1.x + 10;|] @@ -545,14 +545,14 @@ var q = /*b*/ //c /*j*/ 2|] /*k*/ //l /*m*/; /*n*/ //o`); - testExtractFunction("extractFunction_NamelessClass", ` + testExtractFunction("extractFunction_NamelessClass", ` export default class { M() { [#|1 + 1|]; } }`); - testExtractFunction("extractFunction_NoDeclarations", ` + testExtractFunction("extractFunction_NoDeclarations", ` function F() { [#|arguments.length|]; // arguments has no declaration }`); diff --git a/src/testRunner/unittests/services/extract/ranges.ts b/src/testRunner/unittests/services/extract/ranges.ts index 265dd33e60a..d2ac6a0a883 100644 --- a/src/testRunner/unittests/services/extract/ranges.ts +++ b/src/testRunner/unittests/services/extract/ranges.ts @@ -177,7 +177,7 @@ namespace ts { }); testExtractRangeFailed("extractRangeFailed1", - ` + ` namespace A { function f() { [#| @@ -188,13 +188,11 @@ function f() { |] } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]); testExtractRangeFailed("extractRangeFailed2", - ` + ` namespace A { function f() { while (true) { @@ -207,13 +205,11 @@ function f() { } } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); testExtractRangeFailed("extractRangeFailed3", - ` + ` namespace A { function f() { while (true) { @@ -226,13 +222,11 @@ function f() { } } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); testExtractRangeFailed("extractRangeFailed4", - ` + ` namespace A { function f() { l1: { @@ -245,13 +239,11 @@ function f() { } } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message]); testExtractRangeFailed("extractRangeFailed5", - ` + ` namespace A { function f() { [#| @@ -266,13 +258,11 @@ function f() { function f2() { } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]); testExtractRangeFailed("extractRangeFailed6", - ` + ` namespace A { function f() { [#| @@ -287,134 +277,108 @@ function f() { function f2() { } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]); testExtractRangeFailed("extractRangeFailed7", - ` + ` function test(x: number) { while (x) { x--; [#|break;|] } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); testExtractRangeFailed("extractRangeFailed8", - ` + ` function test(x: number) { switch (x) { case 1: [#|break;|] } } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); testExtractRangeFailed("extractRangeFailed9", - `var x = ([#||]1 + 2);`, - [ - refactor.extractSymbol.Messages.cannotExtractEmpty.message - ]); + `var x = ([#||]1 + 2);`, + [refactor.extractSymbol.Messages.cannotExtractEmpty.message]); testExtractRangeFailed("extractRangeFailed10", - ` - function f() { - return 1 + [#|2 + 3|]; + ` + function f() { + return 1 + [#|2 + 3|]; + } } - } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRange.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRange.message]); testExtractRangeFailed("extractRangeFailed11", - ` - function f(x: number) { - while (true) { - [#|try { - x++; + ` + function f(x: number) { + while (true) { + [#|try { + x++; + } + finally { + break; + }|] } - finally { - break; - }|] } - } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message - ]); + `, + [refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]); testExtractRangeFailed("extractRangeFailed12", - `let [#|x|];`, - [ - refactor.extractSymbol.Messages.statementOrExpressionExpected.message - ]); + `let [#|x|];`, + [refactor.extractSymbol.Messages.statementOrExpressionExpected.message]); testExtractRangeFailed("extractRangeFailed13", - `[#|return;|]`, - [ - refactor.extractSymbol.Messages.cannotExtractRange.message - ]); + `[#|return;|]`, + [refactor.extractSymbol.Messages.cannotExtractRange.message]); testExtractRangeFailed("extractRangeFailed14", - ` - switch(1) { - case [#|1: - break;|] - } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRange.message - ]); + ` + switch(1) { + case [#|1: + break;|] + } + `, + [refactor.extractSymbol.Messages.cannotExtractRange.message]); testExtractRangeFailed("extractRangeFailed15", - ` - switch(1) { - case [#|1: - break|]; - } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRange.message - ]); + ` + switch(1) { + case [#|1: + break|]; + } + `, + [refactor.extractSymbol.Messages.cannotExtractRange.message]); // Documentation only - it would be nice if the result were [$|1|] testExtractRangeFailed("extractRangeFailed16", - ` - switch(1) { - [#|case 1|]: - break; - } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRange.message - ]); + ` + switch(1) { + [#|case 1|]: + break; + } + `, + [refactor.extractSymbol.Messages.cannotExtractRange.message]); // Documentation only - it would be nice if the result were [$|1|] testExtractRangeFailed("extractRangeFailed17", - ` - switch(1) { - [#|case 1:|] - break; - } - `, - [ - refactor.extractSymbol.Messages.cannotExtractRange.message - ]); + ` + switch(1) { + [#|case 1:|] + break; + } + `, + [refactor.extractSymbol.Messages.cannotExtractRange.message]); testExtractRangeFailed("extractRangeFailed18", - `[#|{ 1;|] }`, - [ - refactor.extractSymbol.Messages.cannotExtractRange.message - ]); + `[#|{ 1;|] }`, + [refactor.extractSymbol.Messages.cannotExtractRange.message]); testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [refactor.extractSymbol.Messages.cannotExtractIdentifier.message]); }); diff --git a/src/testRunner/unittests/services/languageService.ts b/src/testRunner/unittests/services/languageService.ts index 8f67c1406e5..a5f38eb323b 100644 --- a/src/testRunner/unittests/services/languageService.ts +++ b/src/testRunner/unittests/services/languageService.ts @@ -14,7 +14,7 @@ class Carousel extends Vue { "vue.d.ts": `export namespace Vue { export type Config = { template: string }; }`, "vue-class-component.d.ts": `import Vue from "./vue"; export function Component(x: Config): any;` -}; + }; // Regression test for GH #18245 - bug in single line comment writer caused a debug assertion when attempting // to write an alias to a module's default export was referrenced across files and had no default export it("should be able to create a language service which can respond to deinition requests without throwing", () => { diff --git a/src/testRunner/unittests/services/organizeImports.ts b/src/testRunner/unittests/services/organizeImports.ts index 198d1cb3262..db6dfa8c83c 100644 --- a/src/testRunner/unittests/services/organizeImports.ts +++ b/src/testRunner/unittests/services/organizeImports.ts @@ -344,9 +344,9 @@ import { } from "lib"; libFile); testOrganizeImports("Unused_false_positive_module_augmentation", - { - path: "/test.d.ts", - content: ` + { + path: "/test.d.ts", + content: ` import foo from 'foo'; import { Caseless } from 'caseless'; @@ -356,12 +356,12 @@ declare module 'caseless' { test(name: KeyType): boolean; } }` - }); + }); testOrganizeImports("Unused_preserve_imports_for_module_augmentation_in_non_declaration_file", - { - path: "/test.ts", - content: ` + { + path: "/test.ts", + content: ` import foo from 'foo'; import { Caseless } from 'caseless'; @@ -371,10 +371,10 @@ declare module 'caseless' { test(name: KeyType): boolean; } }` - }); + }); testOrganizeImports("Unused_false_positive_shorthand_assignment", - { + { path: "/test.ts", content: ` import { x } from "a"; @@ -383,7 +383,7 @@ const o = { x }; }); testOrganizeImports("Unused_false_positive_export_shorthand", - { + { path: "/test.ts", content: ` import { x } from "a"; diff --git a/src/testRunner/unittests/services/preProcessFile.ts b/src/testRunner/unittests/services/preProcessFile.ts index c0a47779837..766c7d7078b 100644 --- a/src/testRunner/unittests/services/preProcessFile.ts +++ b/src/testRunner/unittests/services/preProcessFile.ts @@ -167,24 +167,24 @@ describe("unittests:: services:: PreProcessFile:", () => { "import {a as A} from \"m5\";" + "\n" + "import {a as A, b, c as C} from \"m6\";" + "\n" + "import def , {a, b, c as C} from \"m7\";" + "\n", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m1", pos: 20, end: 22 }, - { fileName: "m2", pos: 51, end: 53 }, - { fileName: "m3", pos: 73, end: 75 }, - { fileName: "m4", pos: 95, end: 97 }, - { fileName: "m5", pos: 122, end: 124 }, - { fileName: "m6", pos: 160, end: 162 }, - { fileName: "m7", pos: 199, end: 201 } - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m1", pos: 20, end: 22 }, + { fileName: "m2", pos: 51, end: 53 }, + { fileName: "m3", pos: 73, end: 75 }, + { fileName: "m4", pos: 95, end: 97 }, + { fileName: "m5", pos: 122, end: 124 }, + { fileName: "m6", pos: 160, end: 162 }, + { fileName: "m7", pos: 199, end: 201 } + ], + ambientExternalModules: undefined, + isLibFile: false + }); }); it("Correctly return ES6 exports", () => { @@ -192,41 +192,40 @@ describe("unittests:: services:: PreProcessFile:", () => { "export {a} from \"m2\";" + "\n" + "export {a as A} from \"m3\";" + "\n" + "export {a as A, b, c as C} from \"m4\";" + "\n", - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m1", pos: 14, end: 16 }, - { fileName: "m2", pos: 36, end: 38 }, - { fileName: "m3", pos: 63, end: 65 }, - { fileName: "m4", pos: 101, end: 103 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m1", pos: 14, end: 16 }, + { fileName: "m2", pos: 36, end: 38 }, + { fileName: "m3", pos: 63, end: 65 }, + { fileName: "m4", pos: 101, end: 103 }, + ], + ambientExternalModules: undefined, + isLibFile: false + }); }); it("Correctly return ambient external modules", () => { - test(` + test(` declare module A {} declare module "B" {} function foo() { } `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ false, - - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [], - ambientExternalModules: ["B"], - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ false, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [], + ambientExternalModules: ["B"], + isLibFile: false + }); }); it("Correctly handles export import declarations", () => { @@ -251,60 +250,62 @@ describe("unittests:: services:: PreProcessFile:", () => { foo(require('m3')); var z = { f: require('m4') } `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "m1", pos: 39, end: 41 }, - { fileName: "m2", pos: 74, end: 76 }, - { fileName: "m3", pos: 105, end: 107 }, - { fileName: "m4", pos: 146, end: 148 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "m1", pos: 39, end: 41 }, + { fileName: "m2", pos: 74, end: 76 }, + { fileName: "m3", pos: 105, end: 107 }, + { fileName: "m4", pos: 146, end: 148 }, + ], + ambientExternalModules: undefined, + isLibFile: false + }); }); it("Correctly handles dependency lists in define([deplist]) calls in JavaScript files", () => { test(` define(["mod1", "mod2"], (m1, m2) => { }); `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "mod1", pos: 21, end: 25 }, - { fileName: "mod2", pos: 29, end: 33 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "mod1", pos: 21, end: 25 }, + { fileName: "mod2", pos: 29, end: 33 }, + ], + ambientExternalModules: undefined, + isLibFile: false + }); }); + it("Correctly handles dependency lists in define(modName, [deplist]) calls in JavaScript files", () => { test(` define("mod", ["mod1", "mod2"], (m1, m2) => { }); `, - /*readImportFile*/ true, - /*detectJavaScriptImports*/ true, - { - referencedFiles: [], - typeReferenceDirectives: [], - libReferenceDirectives: [], - importedFiles: [ - { fileName: "mod1", pos: 28, end: 32 }, - { fileName: "mod2", pos: 36, end: 40 }, - ], - ambientExternalModules: undefined, - isLibFile: false - }); + /*readImportFile*/ true, + /*detectJavaScriptImports*/ true, + { + referencedFiles: [], + typeReferenceDirectives: [], + libReferenceDirectives: [], + importedFiles: [ + { fileName: "mod1", pos: 28, end: 32 }, + { fileName: "mod2", pos: 36, end: 40 }, + ], + ambientExternalModules: undefined, + isLibFile: false + }); }); + it("correctly handles augmentations in external modules - 1", () => { test(` declare module "../Observable" { diff --git a/src/testRunner/unittests/services/textChanges.ts b/src/testRunner/unittests/services/textChanges.ts index 27195c30034..bb68e2780bd 100644 --- a/src/testRunner/unittests/services/textChanges.ts +++ b/src/testRunner/unittests/services/textChanges.ts @@ -84,14 +84,14 @@ namespace M runSingleFileTest("extractMethodLike", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { const statements = (findChild("foo", sourceFile)).body!.statements.slice(1); const newFunction = createFunctionDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ "bar", - /*typeParameters*/ undefined, - /*parameters*/ emptyArray, - /*type*/ createKeywordTypeNode(SyntaxKind.AnyKeyword), - /*body */ createBlock(statements) + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ "bar", + /*typeParameters*/ undefined, + /*parameters*/ emptyArray, + /*type*/ createKeywordTypeNode(SyntaxKind.AnyKeyword), + /*body */ createBlock(statements) ); changeTracker.insertNodeBefore(sourceFile, /*before*/findChild("M2", sourceFile), newFunction); @@ -183,12 +183,12 @@ var a = 4; // comment 7 } function createTestClass() { return createClassDeclaration( - /*decorators*/ undefined, + /*decorators*/ undefined, [ createToken(SyntaxKind.PublicKeyword) ], "class1", - /*typeParameters*/ undefined, + /*typeParameters*/ undefined, [ createHeritageClause( SyntaxKind.ImplementsKeyword, @@ -199,12 +199,12 @@ var a = 4; // comment 7 ], [ createProperty( - /*decorators*/ undefined, - /*modifiers*/ undefined, + /*decorators*/ undefined, + /*modifiers*/ undefined, "property1", - /*questionToken*/ undefined, + /*questionToken*/ undefined, createKeywordTypeNode(SyntaxKind.BooleanKeyword), - /*initializer*/ undefined + /*initializer*/ undefined ) ] ); @@ -336,8 +336,8 @@ namespace M { function createTestSuperCall() { const superCall = createCall( createSuper(), - /*typeArguments*/ undefined, - /*argumentsArray*/ emptyArray + /*typeArguments*/ undefined, + /*argumentsArray*/ emptyArray ); return createStatement(superCall); } diff --git a/src/testRunner/unittests/services/transpile.ts b/src/testRunner/unittests/services/transpile.ts index 2ce29f5329b..6ab51138c12 100644 --- a/src/testRunner/unittests/services/transpile.ts +++ b/src/testRunner/unittests/services/transpile.ts @@ -83,8 +83,8 @@ namespace ts { transpilesCorrectly("Generates no diagnostics for missing file references", `/// var x = 0;`, { - options: { compilerOptions: { module: ModuleKind.CommonJS } } - }); + options: { compilerOptions: { module: ModuleKind.CommonJS } } + }); transpilesCorrectly("Generates no diagnostics for missing module imports", `import {a} from "module2";`, { options: { compilerOptions: { module: ModuleKind.CommonJS } } @@ -410,17 +410,18 @@ var x = 0;`, { `export class MyClass1 {` + ` constructor(private _elementRef: ng.ElementRef){}` + `}`, { - options: { - compilerOptions: { - target: ScriptTarget.ES5, - module: ModuleKind.CommonJS, - moduleResolution: ModuleResolutionKind.NodeJs, - emitDecoratorMetadata: true, - experimentalDecorators: true, - isolatedModules: true, + options: { + compilerOptions: { + target: ScriptTarget.ES5, + module: ModuleKind.CommonJS, + moduleResolution: ModuleResolutionKind.NodeJs, + emitDecoratorMetadata: true, + experimentalDecorators: true, + isolatedModules: true, + } } } - }); + ); transpilesCorrectly("Correctly serialize metadata when transpile with System option", `import * as ng from "angular2/core";` + @@ -429,17 +430,18 @@ var x = 0;`, { `export class MyClass1 {` + ` constructor(private _elementRef: ng.ElementRef){}` + `}`, { - options: { - compilerOptions: { - target: ScriptTarget.ES5, - module: ModuleKind.System, - moduleResolution: ModuleResolutionKind.NodeJs, - emitDecoratorMetadata: true, - experimentalDecorators: true, - isolatedModules: true, + options: { + compilerOptions: { + target: ScriptTarget.ES5, + module: ModuleKind.System, + moduleResolution: ModuleResolutionKind.NodeJs, + emitDecoratorMetadata: true, + experimentalDecorators: true, + isolatedModules: true, + } } } - }); + ); transpilesCorrectly("Supports readonly keyword for arrays", "let x: readonly string[];", { options: { compilerOptions: { module: ModuleKind.CommonJS } } diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index 376b7d16ec8..1fc29927936 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -119,28 +119,28 @@ namespace ts { class C { foo = 10; static bar = 20 } namespace C { export let x = 10; } `, { - transformers: { - before: [forceNamespaceRewrite], - }, - compilerOptions: { - target: ScriptTarget.ESNext, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + transformers: { + before: [forceNamespaceRewrite], + }, + compilerOptions: { + target: ScriptTarget.ESNext, + newLine: NewLineKind.CarriageReturnLineFeed, + } + }).outputText; }); testBaseline("transformTypesInExportDefault", () => { return transpileModule(` export default (foo: string) => { return 1; } `, { - transformers: { - before: [replaceNumberWith2], - }, - compilerOptions: { - target: ScriptTarget.ESNext, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + transformers: { + before: [replaceNumberWith2], + }, + compilerOptions: { + target: ScriptTarget.ESNext, + newLine: NewLineKind.CarriageReturnLineFeed, + } + }).outputText; }); testBaseline("synthesizedClassAndNamespaceCombination", () => { @@ -326,14 +326,14 @@ namespace ts { const exportedSeparately = 2; export {exportedSeparately}; `, { - transformers: { - before: [addSyntheticComment(isVariableStatement)], - }, - compilerOptions: { - target: ScriptTarget.ES5, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + transformers: { + before: [addSyntheticComment(isVariableStatement)], + }, + compilerOptions: { + target: ScriptTarget.ES5, + newLine: NewLineKind.CarriageReturnLineFeed, + } + }).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 @@ -347,14 +347,14 @@ export { /* specifier comment */ X, Y} from 'somewhere'; export * from 'somewhere'; export {Value}; `, { - transformers: { - before: [addSyntheticComment(n => isImportDeclaration(n) || isExportDeclaration(n) || isImportSpecifier(n) || isExportSpecifier(n))], - }, - compilerOptions: { - target: ScriptTarget.ES5, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + transformers: { + before: [addSyntheticComment(n => isImportDeclaration(n) || isExportDeclaration(n) || isImportSpecifier(n) || isExportSpecifier(n))], + }, + compilerOptions: { + target: ScriptTarget.ES5, + newLine: NewLineKind.CarriageReturnLineFeed, + } + }).outputText; }); // https://github.com/Microsoft/TypeScript/issues/17594 @@ -370,14 +370,14 @@ class Clazz { constructor(readonly field = 1) {} } `, { - transformers: { - before: [addSyntheticComment(n => isPropertyDeclaration(n) || isParameterPropertyDeclaration(n) || isClassDeclaration(n) || isConstructorDeclaration(n))], - }, - compilerOptions: { - target: ScriptTarget.ES2015, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + transformers: { + before: [addSyntheticComment(n => isPropertyDeclaration(n) || isParameterPropertyDeclaration(n) || isClassDeclaration(n) || isConstructorDeclaration(n))], + }, + compilerOptions: { + target: ScriptTarget.ES2015, + newLine: NewLineKind.CarriageReturnLineFeed, + } + }).outputText; }); testBaseline("transformAddCommentToNamespace", () => { @@ -391,14 +391,14 @@ namespace Foo { export const y = 1; } `, { - transformers: { - before: [addSyntheticComment(n => isModuleDeclaration(n))], - }, - compilerOptions: { - target: ScriptTarget.ES2015, - newLine: NewLineKind.CarriageReturnLineFeed, - } - }).outputText; + transformers: { + before: [addSyntheticComment(n => isModuleDeclaration(n))], + }, + compilerOptions: { + target: ScriptTarget.ES2015, + newLine: NewLineKind.CarriageReturnLineFeed, + } + }).outputText; }); // https://github.com/Microsoft/TypeScript/issues/24709 @@ -410,9 +410,9 @@ namespace Foo { const host = new fakes.CompilerHost(fs); host.getSourceFile = () => transformedSourceFile; const program = createProgram(["source.ts"], { - target: ScriptTarget.ES3, - module: ModuleKind.None, - noLib: true + target: ScriptTarget.ES3, + module: ModuleKind.None, + noLib: true }, host); program.emit(transformedSourceFile, (_p, s, b) => host.writeFile("source.js", s, b)); return host.readFile("source.js")!.toString(); @@ -421,18 +421,18 @@ namespace Foo { const visitor: Visitor = (node) => { if (isMethodDeclaration(node)) { return updateMethod( - node, - node.decorators, - node.modifiers, - node.asteriskToken, - createIdentifier("foobar"), - node.questionToken, - node.typeParameters, - node.parameters, - node.type, - node.body, + node, + node.decorators, + node.modifiers, + node.asteriskToken, + createIdentifier("foobar"), + node.questionToken, + node.typeParameters, + node.parameters, + node.type, + node.body, ); - } + } return visitEachChild(node, visitor, context); }; return (node: SourceFile) => visitNode(node, visitor); diff --git a/src/testRunner/unittests/tsbuild/helpers.ts b/src/testRunner/unittests/tsbuild/helpers.ts index 7aeaba36199..9cdca02a0b8 100644 --- a/src/testRunner/unittests/tsbuild/helpers.ts +++ b/src/testRunner/unittests/tsbuild/helpers.ts @@ -203,8 +203,7 @@ declare const console: { log(msg: any): void; };`; const actual = actualReadFileMap.get(expectedFile); assert.equal(actual, expected, `Mismatch in read file call number for: ${expectedFile} Not in Actual: ${JSON.stringify(arrayFrom(mapDefinedIterator(expectedReadFiles.keys(), f => actualReadFileMap.has(f) ? undefined : f)))} -Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIterator(actualReadFileMap.entries(), - ([p, v]) => expectedReadFiles.get(p) !== v ? [p, v, expectedReadFiles.get(p) || 0] : undefined)))}`); +Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIterator(actualReadFileMap.entries(), ([p, v]) => expectedReadFiles.get(p) !== v ? [p, v, expectedReadFiles.get(p) || 0] : undefined)))}`); }); } diff --git a/src/testRunner/unittests/tsbuild/sample.ts b/src/testRunner/unittests/tsbuild/sample.ts index df2fb62db25..cb3712cb951 100644 --- a/src/testRunner/unittests/tsbuild/sample.ts +++ b/src/testRunner/unittests/tsbuild/sample.ts @@ -906,7 +906,7 @@ class someClass { }`), "target": "esnext", } }`); - }, + }, expectedDiagnostics: [ getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json"), [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/core/anotherModule.js"], diff --git a/src/testRunner/unittests/tscWatch/emit.ts b/src/testRunner/unittests/tscWatch/emit.ts index 06aec75f31f..01264019962 100644 --- a/src/testRunner/unittests/tscWatch/emit.ts +++ b/src/testRunner/unittests/tscWatch/emit.ts @@ -383,9 +383,9 @@ namespace ts.tscWatch { const { moduleFile1, verifyAffectedFiles } = getInitialState({ - configObj: { compilerOptions: { module: "system", outFile: outFilePath } }, - getEmitLine: (_, host) => getEmittedLineForSingleFileOutput(outFilePath, host) - }); + configObj: { compilerOptions: { module: "system", outFile: outFilePath } }, + getEmitLine: (_, host) => getEmittedLineForSingleFileOutput(outFilePath, host) + }); moduleFile1.content = `export var T: number;export function Foo() { };`; verifyAffectedFiles([moduleFile1]); @@ -399,8 +399,8 @@ namespace ts.tscWatch { const { moduleFile1, file1Consumer1, file1Consumer2, verifyAffectedFiles, getFile } = getInitialState({ - getAdditionalFileOrFolder: () => [file1Consumer1Consumer1] - }); + getAdditionalFileOrFolder: () => [file1Consumer1Consumer1] + }); const file1Consumer1Consumer1Emit = getFile(file1Consumer1Consumer1.path); file1Consumer1.content += "export var T: number;"; @@ -436,10 +436,10 @@ namespace ts.tscWatch { getFile, verifyAffectedFiles } = getInitialState({ - firstCompilationEmitFiles: [file1.path, file2.path], - getAdditionalFileOrFolder: () => [file1, file2], - firstReloadFileList: [libFile.path, file1.path, file2.path, configFilePath] - }); + firstCompilationEmitFiles: [file1.path, file2.path], + getAdditionalFileOrFolder: () => [file1, file2], + firstReloadFileList: [libFile.path, file1.path, file2.path, configFilePath] + }); const file1Emit = getFile(file1.path), file2Emit = getFile(file2.path); file1Emit.content += "export var t3 = 10;"; @@ -459,10 +459,10 @@ namespace ts.tscWatch { getFile, verifyAffectedFiles } = getInitialState({ - firstCompilationEmitFiles: [referenceFile1.path, moduleFile1Path], - getAdditionalFileOrFolder: () => [referenceFile1], - firstReloadFileList: [libFile.path, referenceFile1.path, moduleFile1Path, configFilePath] - }); + firstCompilationEmitFiles: [referenceFile1.path, moduleFile1Path], + getAdditionalFileOrFolder: () => [referenceFile1], + firstReloadFileList: [libFile.path, referenceFile1.path, moduleFile1Path, configFilePath] + }); const referenceFile1Emit = getFile(referenceFile1.path); verifyAffectedFiles([referenceFile1Emit], [libFile, referenceFile1Emit, configFile]); @@ -481,10 +481,10 @@ namespace ts.tscWatch { getFile, verifyAffectedFiles } = getInitialState({ - firstCompilationEmitFiles: [referenceFile1.path], - getAdditionalFileOrFolder: () => [referenceFile1], - firstReloadFileList: [libFile.path, referenceFile1.path, configFilePath] - }); + firstCompilationEmitFiles: [referenceFile1.path], + getAdditionalFileOrFolder: () => [referenceFile1], + firstReloadFileList: [libFile.path, referenceFile1.path, configFilePath] + }); const referenceFile1Emit = getFile(referenceFile1.path); referenceFile1Emit.content += "export var yy = Foo();"; diff --git a/src/testRunner/unittests/tsserver/metadataInResponse.ts b/src/testRunner/unittests/tsserver/metadataInResponse.ts index 6ec8a565d87..a2df56e6ee5 100644 --- a/src/testRunner/unittests/tsserver/metadataInResponse.ts +++ b/src/testRunner/unittests/tsserver/metadataInResponse.ts @@ -77,11 +77,11 @@ namespace ts.projectSystem { command: protocol.CommandTypes.CompletionInfo, arguments: completionRequestArgs }, { - isGlobalCompletion: false, - isMemberCompletion: true, - isNewIdentifierLocation: false, - entries: expectedCompletionEntries - }); + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: false, + entries: expectedCompletionEntries + }); }); it("returns undefined correctly", () => { diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index c46a13766d8..95c6d9239b4 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -382,76 +382,76 @@ namespace ts.server { break; } case EventInitializationFailed: { - const body: protocol.TypesInstallerInitializationFailedEventBody = { - message: response.message - }; - const eventName: protocol.TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; - this.event(body, eventName); - break; - } + const body: protocol.TypesInstallerInitializationFailedEventBody = { + message: response.message + }; + const eventName: protocol.TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; + this.event(body, eventName); + break; + } case EventBeginInstallTypes: { - const body: protocol.BeginInstallTypesEventBody = { - eventId: response.eventId, - packages: response.packagesToInstall, - }; - const eventName: protocol.BeginInstallTypesEventName = "beginInstallTypes"; - this.event(body, eventName); - break; - } + const body: protocol.BeginInstallTypesEventBody = { + eventId: response.eventId, + packages: response.packagesToInstall, + }; + const eventName: protocol.BeginInstallTypesEventName = "beginInstallTypes"; + this.event(body, eventName); + break; + } case EventEndInstallTypes: { - if (this.telemetryEnabled) { - const body: protocol.TypingsInstalledTelemetryEventBody = { - telemetryEventName: "typingsInstalled", - payload: { - installedPackages: response.packagesToInstall.join(","), - installSuccess: response.installSuccess, - typingsInstallerVersion: response.typingsInstallerVersion - } - }; - const eventName: protocol.TelemetryEventName = "telemetry"; - this.event(body, eventName); - } - - const body: protocol.EndInstallTypesEventBody = { - eventId: response.eventId, - packages: response.packagesToInstall, - success: response.installSuccess, + if (this.telemetryEnabled) { + const body: protocol.TypingsInstalledTelemetryEventBody = { + telemetryEventName: "typingsInstalled", + payload: { + installedPackages: response.packagesToInstall.join(","), + installSuccess: response.installSuccess, + typingsInstallerVersion: response.typingsInstallerVersion + } }; - const eventName: protocol.EndInstallTypesEventName = "endInstallTypes"; + const eventName: protocol.TelemetryEventName = "telemetry"; this.event(body, eventName); - break; } + + const body: protocol.EndInstallTypesEventBody = { + eventId: response.eventId, + packages: response.packagesToInstall, + success: response.installSuccess, + }; + const eventName: protocol.EndInstallTypesEventName = "endInstallTypes"; + this.event(body, eventName); + break; + } case ActionInvalidate: { - this.projectService.updateTypingsForProject(response); - break; - } + this.projectService.updateTypingsForProject(response); + break; + } case ActionSet: { - if (this.activeRequestCount > 0) { - this.activeRequestCount--; - } - else { - Debug.fail("Received too many responses"); - } - - while (this.requestQueue.length > 0) { - const queuedRequest = this.requestQueue.shift()!; - if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) { - this.requestMap.delete(queuedRequest.operationId); - this.scheduleRequest(queuedRequest); - break; - } - - if (this.logger.hasLevel(LogLevel.verbose)) { - this.logger.info(`Skipping defunct request for: ${queuedRequest.operationId}`); - } - } - - this.projectService.updateTypingsForProject(response); - - this.event(response, "setTypings"); - - break; + if (this.activeRequestCount > 0) { + this.activeRequestCount--; } + else { + Debug.fail("Received too many responses"); + } + + while (this.requestQueue.length > 0) { + const queuedRequest = this.requestQueue.shift()!; + if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) { + this.requestMap.delete(queuedRequest.operationId); + this.scheduleRequest(queuedRequest); + break; + } + + if (this.logger.hasLevel(LogLevel.verbose)) { + this.logger.info(`Skipping defunct request for: ${queuedRequest.operationId}`); + } + } + + this.projectService.updateTypingsForProject(response); + + this.event(response, "setTypings"); + + break; + } default: assertType(response); } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 82ab70b6e6f..8bbd7729868 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -8080,6 +8080,15 @@ declare namespace ts.server.protocol { telemetryEventName: TypingsInstalledTelemetryEventName; payload: TypingsInstalledTelemetryEventPayload; } + /** + * __GDPR__ + * "typingsinstalled" : { + * "${include}": ["${TypeScriptCommonProperties}"], + * "installedPackages": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, + * "installSuccess": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + * } + */ interface TypingsInstalledTelemetryEventPayload { /** * Comma separated list of installed typing packages @@ -8645,6 +8654,25 @@ declare namespace ts.server { readonly eventName: typeof ProjectInfoTelemetryEvent; readonly data: ProjectInfoTelemetryEventData; } + /** + * __GDPR__ + * "projectInfo" : { + * "${include}": ["${TypeScriptCommonProperties}"], + * "projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" }, + * "fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, + * "version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } + * } + */ interface ProjectInfoTelemetryEventData { /** Cryptographically secure hash of project file location. */ readonly projectId: string;